嗨,我想创建蜘蛛,每天搜刮一个网站。我有一个蜘蛛,可以搜刮所有我需要的东西,但我需要实现在每篇文章搜刮后暂停。我已经尝试过 threading
模块和 time
模块,但使用它们似乎并不奏效,因为我得到了这样的响应(只从一些请求中得到)。
DEBUG: Retrying <GET https://www.example.com/.../> (failed 1 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionLost: Connection to the other side was lost in a non-clean fashion: Connection lost.>]
.
class AutomatedSpider(scrapy.Spider):
name = 'automated'
allowed_domains = ['example-domain.com']
start_urls = [
'https://example.com/page/1/...'
]
pause = threading.Event()
article_num = 1
def parse(self, response):
for page_num in range(1, 26):
for href in set(response.css(".h-100 a::attr(href)").extract()):
# extract data from all the articles on current page
self.pause.wait(5.0) # this causes the response mentioned above
yield scrapy.Request(href, callback=self.parse_article)
self.article_num += 1
# move to next page
next_page = 'https://www.information-age.com/page/'+str(page_num)+'/...'
yield scrapy.Request(next_page, callback=self.parse)
def parse_article(self, response):
# function to extract desired data from website that is being scraped
我不认为线程中的time.sleep和waits可以在Scrapy中很好地工作,因为它的工作方式是异步的。你可以做的是以下几点。