作者kilfu0701 (享受人生快乐至上)
站内Python
标题Re: [问题] 爬虫问题..
时间Mon Nov 12 16:55:05 2012
※ 引述《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
1F:推 qwertmn:感谢@@" 後面两种做法确实可行.. 11/12 20:34
2F:→ qwertmn:不过还是不了位啥直接parse会死.. 挖一下code XD 11/12 20:35
3F:→ qwertmn:= ="" c code.. 看来还是要找时间看c了.. 11/12 20:43
4F:→ uranusjr:我猜是网页有地方没有关好, parse 很严格, fromstring 可 11/12 21:00
5F:→ uranusjr:以吃 fragments (etree 没仔细研究需求, 我猜也是一样) 11/12 21:01
6F:→ uranusjr:一般而言除非网页是你自己写的, 否则在 parsing 的时候要 11/12 21:02
7F:→ uranusjr:注意 HTML 结构标准比 XML 宽松的问题 11/12 21:02
8F:→ AndCycle:改用beautifulsoup对这种有问题的html容忍度比较高 11/12 22:11
※ 编辑: kilfu0701 来自: 122.116.55.3 (11/13 00:38)
9F:推 qwertmn:感谢@@" 11/13 07:15