小编典典

使用scrapy获取URL列表,然后在这些URL中抓取内容

scrapy

我需要一个Scrapy Spider来为每个URL(30个产品,所以30个URL)抓取以下页面(https://www.phidgets.com/?tier=1&catid=64&pcid=57),然后通过该URL进入每个产品并抓取其中的数据。

我的第二部分完全按照我的意愿工作:

import scrapy

class ProductsSpider(scrapy.Spider):
    name = "products"
    start_urls = [
        'https://www.phidgets.com/?tier=1&catid=64&pcid=57',
    ]

    def parse(self, response):
        for info in response.css('div.ph-product-container'):
            yield {
                'product_name': info.css('h2.ph-product-name::text').extract_first(),
                'product_image': info.css('div.ph-product-img-ctn a').xpath('@href').extract(),
                'sku': info.css('span.ph-pid').xpath('@prod-sku').extract_first(),
                'short_description': info.css('div.ph-product-summary::text').extract_first(),
                'price': info.css('h2.ph-product-price > span.price::text').extract_first(),
                'long_description': info.css('div#product_tab_1').extract_first(),
                'specs': info.css('div#product_tab_2').extract_first(),
            }

        # next_page = response.css('div.ph-summary-entry-ctn a::attr("href")').extract_first()
        # if next_page is not None:
        #     yield response.follow(next_page, self.parse)

但是我不知道如何做第一部分。如你所见,我将主页(https://www.phidgets.com/?tier=1&catid=64&pcid=57)设置为start_url。但是,如何获取我需要抓取的所有30个网址填充到start_urls列表中呢?


阅读 1612

收藏
2020-04-09

共1个答案

小编典典

我目前无法测试,所以请告诉我这是否对你有用,因此如果有任何错误,我可以对其进行编辑。

这里的想法是,我们在首页中找到每个链接,并通过将你的产品解析方法作为回调传递新的scrapy请求

import scrapy
from urllib.parse import urljoin

class ProductsSpider(scrapy.Spider):
    name = "products"
    start_urls = [
        'https://www.phidgets.com/?tier=1&catid=64&pcid=57',
    ]

    def parse(self, response):
        products = response.xpath("//*[contains(@class, 'ph-summary-entry-ctn')]/a/@href").extract()
        for p in products:
            url = urljoin(response.url, p)
            yield scrapy.Request(url, callback=self.parse_product)

    def parse_product(self, response):
        for info in response.css('div.ph-product-container'):
            yield {
                'product_name': info.css('h2.ph-product-name::text').extract_first(),
                'product_image': info.css('div.ph-product-img-ctn a').xpath('@href').extract(),
                'sku': info.css('span.ph-pid').xpath('@prod-sku').extract_first(),
                'short_description': info.css('div.ph-product-summary::text').extract_first(),
                'price': info.css('h2.ph-product-price > span.price::text').extract_first(),
                'long_description': info.css('div#product_tab_1').extract_first(),
                'specs': info.css('div#product_tab_2').extract_first(),
            }
2020-04-09