【发布时间】:2021-10-13 20:39:34
【问题描述】:
在下面的示例中,每个桶都有很多球。任一桶中可能有也可能没有红球。为了确定一个球是否是红色的,我们抓取它。
如果找到一个红球,我想停止爬行其余的球(即我不希望发出下一个球的请求,我知道它不会是红色的,因为我'已经找到了)。
桶和球标识符是基本 URL 的查询参数。
我尝试过的 #1
维护一个类状态并检查一个桶是否已经有红球
class BucketsBallsSpider(scrapy.Spider):
name = 'test_spider'
base_url = 'https://bucketswithballs.com'
buckets = []
balls = []
buckets_with_red_balls = []
def start_requests(self):
for bucket in self.buckets:
for ball in self.balls:
if bucket in self.buckets_with_red_balls:
break
url = add_or_replace_parameter(self.base_url, 'bucket', bucket)
url = add_or_replace_parameter(url, 'ball', ball)
yield scrapy.Request(url, self.parse)
def parse(self, response, **kwargs):
is_red_ball = response.xpath('//*[@id="is_red_ball"]').extract()
if is_red_ball:
bucket_id = url_query_parameter(response.url, 'bucket')
self.buckets_with_red_balls.append(bucket_id)
yield {'bucket_with_red_ball': bucket_id}
我尝试过的 #2
解析方法中的yield请求
class BucketsBallsSpider(scrapy.Spider):
name = 'test_spider'
base_url = 'https://bucketswithballs.com'
buckets = []
balls = []
buckets_with_red_balls = []
def start_requests(self):
# Start from first bucket and first ball
url = add_or_replace_parameter(self.base_url, 'bucket', self.buckets[0])
url = add_or_replace_parameter(url, 'ball', self.balls[0])
yield scrapy.Request(url, self.parse)
def parse(self, response, **kwargs):
is_red_ball = response.xpath('//*[@id="is_red_ball"]').extract()
if is_red_ball:
bucket_id = url_query_parameter(response.url, 'bucket')
self.buckets_with_red_balls.append(bucket_id)
yield {'bucket_with_red_ball': bucket_id}
# Scrapy filter will skip duplicates
for bucket in self.buckets:
for ball in self.balls:
if bucket in self.buckets_with_red_balls:
break
url = add_or_replace_parameter(self.base_url, 'bucket', bucket)
url = add_or_replace_parameter(url, 'ball', ball)
yield scrapy.Request(url, self.parse)
对于每个示例,Scrapy 在控制台中告诉我它抓取了每个 URL。出于性能原因,我想避免这种情况。
【问题讨论】:
标签: python python-3.x scrapy scrapy-pipeline