看板 Python 關於我們 聯絡資訊
※ 引述《qwertmn (抽筋)》之銘言: : 我想抓台南縣觀光旅遊局的資料..網址如下 : http://tour.tainan.gov.tw/action.aspx?season=spring : : 不過我用lxml 分析tag 的結構都不對.. 程式碼如下 : : from lxml import html : import urllib2 : : file = urllib2.urlopen('http://tour.tainan.gov.tw/action.aspx?season=spring') : root = html.parse(file).getroot() : : #這邊都抓不到table... 不過我用chrome 去抓過document tree, 有抓到超過100個... : print root.cssselect('table') : : 不知道我哪邊有做錯了.. : 求救.. 剛剛寫了一個測試了一下,我用了三種方式去parsing html 多加一個google首頁 當做對照組。 結果第一種 也就是原PO的方法,的確會抓不到table, (不過google首頁的 還是有抓到) 其他兩種都沒問題,不確定是不是html的原始碼有問題 以下為測試的程式碼:( http://pastie.org/5364617 ) # -*- coding: utf-8 -*- from lxml import html, etree import urllib2 urls = [ 'http://tour.tainan.gov.tw/action.aspx?season=spring', 'http://www.google.com.tw' ] # case 1: print '== Case 1 : use lxml.html.parse() ==' for url in urls: print " ", url resp = urllib2.urlopen(url) root = html.parse(resp).getroot() print "\t", root.tag for i in root.cssselect('table'): print "\t", i, i.values() print print # case 2: print '== Case 2 : use lxml.html.fromstring() ==' for url in urls: print " ", url resp = urllib2.urlopen(url) doc = html.fromstring(resp.read()) print "\t", doc.tag for i in doc.cssselect('table'): print "\t", i , i.values() print print # case 3: print '== Case 3 : use lxml.etree.HTML() ==' for url in urls: print " ", url resp = urllib2.urlopen(url) tree = etree.HTML(resp.read()) print "\t", tree.tag for i in tree.iter('table'): print "\t", i, i.values() print -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 1.34.163.177
qwertmn:感謝@@" 後面兩種做法確實可行.. 11/12 20:34
qwertmn:不過還是不了位啥直接parse會死.. 挖一下code XD 11/12 20:35
qwertmn:= ="" c code.. 看來還是要找時間看c了.. 11/12 20:43
uranusjr:我猜是網頁有地方沒有關好, parse 很嚴格, fromstring 可 11/12 21:00
uranusjr:以吃 fragments (etree 沒仔細研究需求, 我猜也是一樣) 11/12 21:01
uranusjr:一般而言除非網頁是你自己寫的, 否則在 parsing 的時候要 11/12 21:02
uranusjr:注意 HTML 結構標準比 XML 寬鬆的問題 11/12 21:02
AndCycle:改用beautifulsoup對這種有問題的html容忍度比較高 11/12 22:11
※ 編輯: kilfu0701 來自: 122.116.55.3 (11/13 00:38)
qwertmn:感謝@@" 11/13 07:15