首页 > 解决方案 > 如何从网站上抓取项目名称,同时进入一个循环输入项目链接并解析描述?

问题描述

所以我对刮擦和尝试学习刮擦完全是新手。

https://www.killertools.com/Dent-Removal-Aluminum-Steel_c_11.html 对于初学者,如果有超过 1 页的产品可供浏览,我想从两个页面的第一类所有产品中刮取项目名称。

这就是我得到的并且有效:

import scrapy


class QuotesSpider(scrapy.Spider):
    name = 'killertools'
    start_urls = ['https://www.killertools.com/Dent-Removal-Aluminum-Steel_c_11.html',
              ]

def parse(self, response):

    for item in response.css('div.name'):
        yield {'Name': item.xpath('a/text()').get()}


    next_page = response.css('div.paging a:nth-child(4)::attr("href")').get()
    if next_page is not None:
        yield response.follow(next_page, self.parse)

但我想进入每个产品链接,并提取项目描述并将它们作为描述放入词汇表中。我该怎么做呢?

我试过这样的事情:

import scrapy


class QuotesSpider(scrapy.Spider):
    name = 'killertools'
    start_urls = ['https://www.killertools.com/Dent-Removal-Aluminum-Steel_c_11.html',
              ]

def parse(self, response):

    for item in response.css('div.name'):
        yield {'Name': item.xpath('a/text()').get()}
        detail_page = response.css('div.name a::attr("href")').get()
        if detail_page is not None:
            yield response.follow(detail_page)
            for detail in response.css('div.item'):
                yield {'Description': detail.xpath('p/strong/text').get()}

    next_page = response.css('div.paging a:nth-child(4)::attr("href")').get()
    if next_page is not None:
        yield response.follow(next_page, self.parse)

但它做了一些奇怪的事情,在我的水平上我无法真正理解。

标签: pythonscrapy

解决方案


对于初学者,如果有超过 1 页的产品可供浏览,我想从两个页面的第一类中的所有产品中抓取项目名称。

建议 0

试着用 XPATH 包住你的脑袋!

建议一

在页面底部,靠近分页链接,您会找到“查看全部”。这将添加?viewall=1到原始 URL。对于您提供的 URL,所有 21 个项目都放在一个上。似乎您不再需要担心分页。

建议二

为了获取产品描述,可以设想一个两步过程:

  1. 收集产品页面的 URL
    response.xpath('//div[contains(@class, "product-item")]/div[@class="name"]/a/@href').getall()
    应该可以让您非常接近。
    检查网址。您可能需要预先添加基本网址。urllib是你这里的恶魔。
  2. 运行第二个爬虫来处理所有这些链接并从那里读取描述
    在产品页面上,您会以一种结构良好的方式找到描述:
    response.xpath('//div[@itemprop="description"]/ul/li/text()').getall()
    将为您提供项目符号后面的所有行。

建议 3

善待!不要用不必要的请求锤击他们的网站。测试时,您的自定义设置应包括'HTTPCACHE_ENABLED': True. 查看HTTPCACHE了解详细信息。

祝好运并玩得开心点!


推荐阅读