【发布时间】:2016-05-22 08:14:35
【问题描述】:
我的蜘蛛有点问题。我使用splash和scrapy来获取由JavaScript生成的“下一页”的链接。从第一页下载信息后,我想从以下页面下载信息,但 LinkExtractor 功能无法正常工作。但看起来 start_request 函数不起作用。这是代码:
class ReutersBusinessSpider(CrawlSpider):
name = 'reuters_business'
allowed_domains = ["reuters.com"]
start_urls = (
'http://reuters.com/news/archive/businessNews?view=page&page=1',
)
def start_requests(self):
for url in self.start_urls:
yield scrapy.Request(url, self.parse, meta={
'splash': {
'endpoint': 'render.html',
'args': {'wait': 0.5}
}
})
def use_splash(self, request):
request.meta['splash'] = {
'endpoint':'render.html',
'args':{
'wait':0.5,
}
}
return request
def process_value(value):
m = re.search(r'(\?view=page&page=[0-9]&pageSize=10)', value)
if m:
return urlparse.urljoin('http://reuters.com/news/archive/businessNews',m.group(1))
rules = (
Rule(LinkExtractor(restrict_xpaths='//*[@class="pageNext"]',process_value='process_value'),process_request='use_splash', follow=False),
Rule(LinkExtractor(restrict_xpaths='//h2/*[contains(@href,"article")]',process_value='process_value'),callback='parse_item'),
)
def parse_item(self, response):
l = ItemLoader(item=PajaczekItem(), response=response)
l.add_xpath('articlesection','//span[@class="article-section"]/text()', MapCompose(unicode.strip), Join())
l.add_xpath('date','//span[@class="timestamp"]/text()', MapCompose(parse))
l.add_value('url',response.url)
l.add_xpath('articleheadline','//h1[@class="article-headline"]/text()', MapCompose(unicode.title))
l.add_xpath('articlelocation','//span[@class="location"]/text()')
l.add_xpath('articletext','//span[@id="articleText"]//p//text()', MapCompose(unicode.strip), Join())
return l.load_item()
日志:
2016-02-12 08:20:29 [scrapy] INFO: Spider opened 2016-02-12 08:20:29 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-02-12 08:20:29 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2016-02-12 08:20:38 [scrapy] DEBUG: Crawled (200) <POST localhost:8050/render.html>; (referer: None)
2016-02-12 08:20:38 [scrapy] DEBUG: Filtered offsite request to 'localhost': <GET http://localhost:8050/render.html?page=2&pageSize=10&view=page%3E;
2016-02-12 08:20:38 [scrapy] INFO: Closing spider (finished)
哪里出错了?感谢您的帮助。
【问题讨论】:
-
"但是 LinkExtractor 函数不能正常工作。但是 start_request 函数似乎不能正常工作。" 你看到了什么?你期望什么?你能分享你的日志吗?
-
2016-02-12 08:20:29 [scrapy] 信息:Spider 打开 2016-02-12 08:20:29 [scrapy] 信息:已抓取 0 页(0 页/分钟) ,刮掉 0 件(0 件/分钟) 2016-02-12 08:20:29 [scrapy] 调试:Telnet 控制台正在侦听 127.0.0.1:6023 2016-02-12 08:20:38 [scrapy] 调试:已爬网 (200)
localhost:8050/render.html> (referer: None) 2016-02-12 08:20:38 [scrapy] 调试:过滤到“localhost”的异地请求: localhost:8050/render.html?page=2&pageSize=10&view=page> 2016-02-12 08 :20:38 [scrapy] 信息:关闭蜘蛛(完成) -
已经提供的答案可能是事情不起作用的主要原因。但我也注意到您将回调作为字符串传递给 LinkExtractor 类。您应该找到一些 LinkExtractor 用法示例,以了解如何指定回调(例如
self.process_value,而不是'process_value')。