简体   繁体   English

如何在没有请求的情况下在 Scrapy 中屈服?

[英]How to yield in Scrapy without a request?

I am trying to crawl a defined list of URLs with Scrapy 2.4 where each of those URLs can have up to 5 paginated URLs that I want to follow.我正在尝试使用 Scrapy 2.4 抓取已定义的 URL 列表,其中每个 URL 最多可以有 5 个我想要关注的分页 URL。

Now also the system works, I do have one extra request I want to get rid of:现在系统也可以工作了,我确实有一个额外的请求要摆脱:

Those pages are exactly the same but have a different URL:这些页面完全相同,但具有不同的 URL:

example.html
example.thml?pn=1

Somewhere in my code I do this extra request and I can not figure out how to surpress it.在我的代码中的某个地方,我做了这个额外的请求,但我不知道如何抑制它。

This is the working code:这是工作代码:

Define a bunch of URLs to scrape:定义一堆要抓取的 URL:

start_urls = [
    'https://example...',
    'https://example2...',
]

Start requesting all start urls;开始请求所有开始 url;

def start_requests(self):
    for url in self.start_urls:
        yield scrapy.Request(
            url = url,
            callback=self.parse,
        )

Parse the start URL:解析开始URL:

def parse(self, response):
    url = response.url  + '&pn='+str(1)
    yield scrapy.Request(url, self.parse_item, cb_kwargs=dict(pn=1, base_url=response.url))

Go get all paginated URLs from the start URLs; Go 从起始 URL 获取所有分页 URL;

def parse_item(self, response, pn, base_url):
    self.logger.info('Parsing %s', response.url)        
    if pn < 6: # maximum level 5
        url = base_url + '&pn='+str(pn+1)
        yield scrapy.Request(url, self.parse_item, cb_kwargs=dict(base_url=base_url,pn=pn+1))

If I understand you're question correct you just need to change to start at?pn=1 and ignore the one without pn=null, here's an option how i would do it, which also only requires one parse method.如果我理解你的问题是正确的,你只需要更改为从?pn=1 开始并忽略没有 pn=null 的那个,这是我将如何做的一个选项,它也只需要一个解析方法。

start_urls = [
    'https://example...',
    'https://example2...',
]

def start_requests(self):
    for url in self.start_urls:
        #how many pages to crawl
        for i in range(1,6):
            yield scrapy.Request(
                url=url + f'&pn={str(i)}'
            )

def parse(self, response):
    self.logger.info('Parsing %s', response.url) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM