无法使用Scrapy刮下一页内容

2024-09-30 10:29:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我也想把下一页的内容刮下来,但没有转到下一页。我的代码是:

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,因为下一个页面的url会给出整个url。我还尝试了yield函数中的dont\u filter=true参数,它给了我一个通过第一页的无限循环。我从终端收到的信息是[scrapy.SpiderMiddleware.场外]调试:已筛选的“到”的异地请求www.startech.com.bd': https://www.startech.com.bd/component/processor?页面=2>;


Tags: namecomurlresponsepageextractprocessorxpath
1条回答
网友
1楼 · 发布于 2024-09-30 10:29:58

这是因为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)

相关问题 更多 >

    热门问题