我正在开发一个简单的刮板,可以得到9个gag posts和它的图像,但由于一些技术困难,我无法停止刮板,它继续刮我不想。我想增加计数器值,100个posts后停止。 但是9gag页面的设计方式是在每个响应中只给出10个post,每次迭代后,我的计数器值重置为10,在这种情况下,我的循环会无限长地运行,永不停止。
# -*- coding: utf-8 -*-
import scrapy
from _9gag.items import GagItem
class FirstSpider(scrapy.Spider):
name = "first"
allowed_domains = ["9gag.com"]
start_urls = (
'http://www.9gag.com/',
)
last_gag_id = None
def parse(self, response):
count = 0
for article in response.xpath('//article'):
gag_id = article.xpath('@data-entry-id').extract()
count +=1
if gag_id:
if (count != 100):
last_gag_id = gag_id[0]
ninegag_item = GagItem()
ninegag_item['entry_id'] = gag_id[0]
ninegag_item['url'] = article.xpath('@data-entry-url').extract()[0]
ninegag_item['votes'] = article.xpath('@data-entry-votes').extract()[0]
ninegag_item['comments'] = article.xpath('@data-entry-comments').extract()[0]
ninegag_item['title'] = article.xpath('.//h2/a/text()').extract()[0].strip()
ninegag_item['img_url'] = article.xpath('.//div[1]/a/img/@src').extract()
yield ninegag_item
else:
break
next_url = 'http://9gag.com/?id=%s&c=200' % last_gag_id
yield scrapy.Request(url=next_url, callback=self.parse)
print count
items.py的代码在这里
from scrapy.item import Item, Field
class GagItem(Item):
entry_id = Field()
url = Field()
votes = Field()
comments = Field()
title = Field()
img_url = Field()
所以我想增加一个全局计数值,并尝试通过传递3个参数来解析函数,它会给出错误
TypeError: parse() takes exactly 3 arguments (2 given)
因此,有没有一种方法可以传递一个全局计数值,并在每次迭代后返回该值,然后在100个post之后停止(假设)。
此处提供整个项目 即使我将POST_LIMIT设置为100,也会发生无限循环,请参见我执行的命令
scrapy crawl first -s POST_LIMIT=10 --output=output.json
有一个内置的设置^{} ,可以通过命令行
-s
参数传递,也可以在设置中更改:scrapy crawl <spider> -s CLOSESPIDER_PAGECOUNT=100
一个小小的警告是,如果您启用了缓存,那么它将把缓存命中数也计算为页面计数。
首先:使用
self.count
并在parse
之外初始化。然后不要阻止项目的解析,而是生成新的requests
。请参见以下代码:count
是parse()
方法的本地,因此不在页之间保留。将所有出现的count
更改为self.count
,使其成为类的实例变量,并且它将在页之间持续存在。相关问题 更多 >
编程相关推荐