首页 > 解决方案 > 在 For 循环中运行 Scrapy 在第一次运行后挂起

问题描述

我想在 for 循环中运行 Scrapy,列表中的每个 URL 一个循环。(注意:我不想要所有这些 URL start_urls,我需要它们一次运行一个)。

twisted.internet.error.ReactorNotRestartable在循环的第一次迭代后,我的第一次尝试给了我错误。

对 SO 的搜索给出了一个先前的答案,说process.start(stop_after_crawl=False)应该可以解决这个问题。这摆脱了 Twisted 错误,但现在只是在循环的第一次迭代后挂起。这不是那个问题的重复。

我目前的代码是:

for url in urls:
    process = CrawlerProcess({
        'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
        'DEPTH_LIMIT': 4
    })

    process.crawl(MySpider, url)
    process.start(stop_after_crawl=False)

第一个 URL 运行良好,然后就挂起:

 'response_received_count': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2018, 8, 12, 21, 12, 29, 963422)}
2018-08-12 22:12:30 [scrapy.core.engine] INFO: Spider closed (finished)

标签: python-3.xscrapytwisted

解决方案


对于使用scrapy循环遍历列表,我认为使用“start_requests”是一个好主意:

def start_requests(self):
    with open('./input/id_urls_10k.csv','r') as csvfile:
        urlreader = csv.reader(csvfile, delimiter=',',quotechar='"')
        for row in urlreader:
            if row[1]=="y":
                yield scrapy.Request(url=row[2],meta={'urlkey':row[0]})

推荐阅读