【发布时间】:2015-06-21 20:20:40
【问题描述】:
我的代码看起来像这样
for row in response.css("div#flexBox_flex_calendar_mainCal table tr.calendar_row"):
print "================"
print row.xpath(".//td[@class='time']/text()").extract()
print row.xpath(".//td[@class='currency']/text()").extract()
print row.xpath(".//td[@class='impact']/span/@title").extract()
print row.xpath(".//td[@class='event']/span/text()").extract()
print row.xpath(".//td[@class='actual']/text()").extract()
print row.xpath(".//td[@class='forecast']/text()").extract()
print row.xpath(".//td[@class='previous']/text()").extract()
print "================"
我可以像这样使用纯 python 获得相同的东西,
from lxml import html
import requests
page = requests.get('http://www.forexfactory.com/calendar.php?day=dec1.2011')
tree = html.fromstring(page.text)
print tree.xpath(".//td[@class='time']/text()")
print tree.xpath(".//td[@class='currency']/text()")
print tree.xpath(".//td[@class='impact']/span/@title")
print tree.xpath(".//td[@class='event']/span/text()")
print tree.xpath(".//td[@class='actual']/text()")
print tree.xpath(".//td[@class='forecast']/text()")
print tree.xpath(".//td[@class='previous']/text()")
但是我需要逐行执行此操作。我第一次尝试移植到 lxml 不起作用:
from lxml import html
import requests
page = requests.get('http://www.forexfactory.com/calendar.php?day=dec1.2011')
tree = html.fromstring(page.text)
for row in tree.css("div#flexBox_flex_calendar_mainCal table tr.calendar_row"):
print row.xpath(".//td[@class='time']/text()")
print row.xpath(".//td[@class='currency']/text()")
print row.xpath(".//td[@class='impact']/span/@title")
print row.xpath(".//td[@class='event']/span/text()")
print row.xpath(".//td[@class='actual']/text()")
print row.xpath(".//td[@class='forecast']/text()")
print row.xpath(".//td[@class='previous']/text()")
将这个scrapy代码移植到纯lxml的正确方法是什么?
编辑:我已经接近了一点。我可以看到一个table{} 对象,我只是不知道怎么走路。
import urllib2
from lxml import etree
#import requests
def wgetUrl(target):
try:
req = urllib2.Request(target)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3')
response = urllib2.urlopen(req)
outtxt = response.read()
response.close()
except:
return ''
return outtxt
url = 'http://www.forexfactory.com/calendar.php?day='
date = 'dec1.2011'
data = wgetUrl(url + date)
parser = etree.HTMLParser()
tree = etree.fromstring(data, parser)
for elem in tree.xpath("//div[@id='flexBox_flex_calendar_mainCal']"):
print elem[0].tag, elem[0].attrib, elem[0].text
# elem[1] is where the table is
print elem[1].tag, elem[1].attrib, elem[1].text
print elem[1]
【问题讨论】: