【问题标题】:Can't scrape next page contents using Scrapy无法使用 Scrapy 抓取下一页内容
【发布时间】:2019-03-08 09:52:50
【问题描述】:

我也想从下一页抓取内容,但它没有转到下一页。我的代码是:

import scrapy
class AggregatorSpider(scrapy.Spider):
name = 'aggregator'
allowed_domains = ['startech.com.bd/component/processor']
start_urls = ['https://startech.com.bd/component/processor']

def parse(self, response):
    processor_details = response.xpath('//*[@class="col-xs-12 col-md-4 product-layout grid"]')
    for processor in processor_details:
        name = processor.xpath('.//h4/a/text()').extract_first()
        price = processor.xpath('.//*[@class="price space-between"]/span/text()').extract_first()
        print ('\n')
        print (name)
        print (price)
        print ('\n')
    next_page_url = response.xpath('//*[@class="pagination"]/li/a/@href').extract_first()
    # absolute_next_page_url = response.urljoin(next_page_url)
    yield scrapy.Request(next_page_url)

我没有使用 urljoin,因为 next_page_url 给了我整个 url。我还尝试了 yield 函数中的 dont_filter=true 参数,这给了我一个通过第一页的无限循环。我从终端收到的消息是 [scrapy.spidermiddlewares.offsite] DEBUG: Filtered offsite request to 'www.startech.com.bd': https://www.startech.com.bd /component/processor?page=2>

【问题讨论】:

    标签: python web-scraping scrapy scrapy-shell


    【解决方案1】:

    这是因为您的allowed_domains 变量错误,请使用allowed_domains = ['www.startech.com.bd'] 而不是(see the doc)

    您还可以修改下一页选择器以避免再次进入页面:

    import scrapy
    class AggregatorSpider(scrapy.Spider):
        name = 'aggregator'
        allowed_domains = ['www.startech.com.bd']
        start_urls = ['https://startech.com.bd/component/processor']
    
        def parse(self, response):
            processor_details = response.xpath('//*[@class="col-xs-12 col-md-4 product-layout grid"]')
            for processor in processor_details:
                name = processor.xpath('.//h4/a/text()').extract_first()
                price = processor.xpath('.//*[@class="price space-between"]/span/text()').extract_first()
                yield({'name': name, 'price': price})
            next_page_url = response.css('.pagination li:last-child a::attr(href)').extract_first()
            if next_page_url:
                yield scrapy.Request(next_page_url)
    

    【讨论】:

    • 我更改了允许的域名,现在它通过了第二页但在第二页之后它没有停止,它再次爬到第一页并显示两次相同的东西。
    • 这是因为你的next_page_url变量,你在分页中取了第一个链接
    • 那么在这种情况下我该怎么办?
    • 两个链接的值相同
    • 你能告诉我任何资源,我可以简要了解这个 css 或 xpath 选择器。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 2021-12-07
    • 2018-03-21
    • 2016-05-20
    相关资源
    最近更新 更多