【发布时间】:2020-07-27 18:19:20
【问题描述】:
我希望我的 scrapy spider 在达到某个请求限制时关闭。我试过但不适合我。它会再次显示输入消息,并且在达到限制之前不会中断。
这就是我想要的:
- 如果我想限制请求数量,请在终端输入
- 在达到限制下继续并中断
下面是代码:
# -*- coding: utf-8 -*-
import scrapy
links_list = open('links.txt').read().split('\n')
class MainSpider(scrapy.Spider):
name = 'main'
allowed_domains = ['www.yellowpages.com']
start_urls = links_list
def parse(self, response):
try:
limit = input('Do you want any limit? reply with [y - n]: ')
if limit == 'y':
limit_count = int(input('Enter the limit (Only a number value): '))
except:
pass
for i in range(limit_count):
i += 1
if i == limit_count:
break
lists = response.xpath('//a[@class="business-name"]')
for each in lists:
link = each.xpath('.//@href').get()
yield response.follow(url=link, callback=self.parse_links)
next_page = response.xpath('//a[contains(@class, "next")]/@href').get()
if next_page:
yield response.follow(url=next_page, callback=self.parse)
def parse_links(self, response):
link = response.url
name = response.xpath('//div[@class="sales-info"]/h1/text()').get()
address = response.xpath('//h2[@class="address"]/text()').get()
website = response.xpath('//a[contains(@class,"website-link")]/@href').get()
phone = response.xpath('//p[@class="phone"]/text()').get()
email = response.xpath('(//a[@class="email-business"])[1]/@href').get()
yield {
"Link": link,
"Name": name,
"Address": address,
"Website": website,
"Phone": phone,
"Email": email,
}
【问题讨论】: