我的管道中有一个方法来检查项目的发布日期是否早于在 mysql 中找到的发布日期,所以让 lastseen
成为从数据库中检索到的最新日期时间:
def process_item(self, item, spider):
if item['post_date'] < lastseen:
# set flag to close_spider
# raise DropItem("old item")
这段代码基本上可以工作,除了:我每小时检查一次网站只是为了获得新帖子,如果我不阻止蜘蛛它会继续在数千页上爬行,如果我在标志上停止蜘蛛,机会是很少有请求不会被处理,因为它们可能会在蜘蛛关闭后返回队列,即使这些请求在发布日期可能较新,话虽如此,是否有更精确的抓取的解决方法?
谢谢,
最佳答案
不确定这是否适合您的设置,但您可以获取 lastseen
当初始化你的蜘蛛时从 MySQL 并停止在你的回调中生成请求当响应包含带有 postdate < lastseen
的项目时,因此基本上移动了逻辑以停止直接在蜘蛛而不是管道内爬行。
有时向你的蜘蛛传递一个参数会更简单
scrapy crawl myspider -a lastseen=20130715
并设置蜘蛛的属性以在回调中进行测试(http://doc.scrapy.org/en/latest/topics/spiders.html#spider-arguments)
class MySpider(BaseSpider):
name = 'myspider'
def __init__(self, lastseen=None):
self.lastseen = lastseen
# ...
def parse_new_items(self, reponse):
follow_next_page = True
# item fetch logic
for element in <some_selector>:
# get post_date
post_date = <extract post_date from element>
# check post_date
if post_date < self.lastseen:
follow_next_page = False
continue
item = MyItem()
# populate item...
yield item
# find next page to crawl
if follow_next_page:
next_page_url = ...
yield Request(url = next_page_url, callback=parse_new_items)
关于python - 如何停止 scrapy 蜘蛛但处理所有想要的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17666295/