gpt4 book ai didi

python - Scrapy延迟请求

转载 作者:太空狗 更新时间:2023-10-29 20:42:04 25 4
gpt4 key购买 nike

每次我运行我的代码时,我的 ip 都会被禁止。我需要帮助将每个请求延迟 10 秒。我试图在代码中放置 DOWNLOAD_DELAY 但它没有给出任何结果。感谢您的帮助。

# item class included here
class DmozItem(scrapy.Item):
# define the fields for your item here like:
link = scrapy.Field()
attr = scrapy.Field()


class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["craigslist.org"]
start_urls = [
"https://washingtondc.craigslist.org/search/fua"
]

BASE_URL = 'https://washingtondc.craigslist.org/'

def parse(self, response):
links = response.xpath('//a[@class="hdrlnk"]/@href').extract()
for link in links:
absolute_url = self.BASE_URL + link
yield scrapy.Request(absolute_url, callback=self.parse_attr)

def parse_attr(self, response):
match = re.search(r"(\w+)\.html", response.url)
if match:
item_id = match.group(1)
url = self.BASE_URL + "reply/nos/vgm/" + item_id

item = DmozItem()
item["link"] = response.url

return scrapy.Request(url, meta={'item': item}, callback=self.parse_contact)

def parse_contact(self, response):
item = response.meta['item']
item["attr"] = "".join(response.xpath("//div[@class='anonemail']//text()").extract())
return item

最佳答案

你需要设置DOWNLOAD_DELAY in settings.py你的项目。请注意,您可能还需要限制并发性。默认情况下,并发数为 8,因此您同时访问了 8 个请求的网站。

# settings.py
DOWNLOAD_DELAY = 1
CONCURRENT_REQUESTS_PER_DOMAIN = 2

Scrapy 1.0 开头你也可以在蜘蛛中放置自定义设置,这样你就可以做这样的事情:

class DmozSpider(Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/",
]

custom_settings = {
"DOWNLOAD_DELAY": 5,
"CONCURRENT_REQUESTS_PER_DOMAIN": 2
}

延迟和并发是按下载器插槽设置的,而不是按请求设置的。要实际检查你有什么下载,你可以尝试这样的事情

def parse(self, response):
"""
"""
delay = self.crawler.engine.downloader.slots["www.dmoz.org"].delay
concurrency = self.crawler.engine.downloader.slots["www.dmoz.org"].concurrency
self.log("Delay {}, concurrency {} for request {}".format(delay, concurrency, response.request))
return

关于python - Scrapy延迟请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com