【问题标题】:Can't select a specific element in Xpath无法在 Xpath 中选择特定元素
【发布时间】:2019-03-11 23:18:19
【问题描述】:

我正在尝试抓取此页面:

https://www.coolblue.nl/en/our-assortment

我成功地抓取了每个类别部分中的几乎所有链接。但是由于某种原因,所有这些“更多..”链接都没有通过,即使它们的 Xpath 应该与其他链接相同。

What I looked for in my inspector

我目前正在做的是寻找属于“a”标签的所有“href”值,类值category-navigation--link

我在 Python 上使用 Scrapy,所以我从脚本中获取信息的方式是:

response.xpath("//a[@class='category-navigation--link']/@href")

这很好地提供了页面中的大多数链接,除了这些“更多..”链接,但我不明白为什么。他们似乎和其他人一样,但是 xpath 选择器不知何故无法获取信息..

编辑:这是我的代码。它应该像这里发布的漂亮汤示例 PS1212 一样工作,唯一的区别是我返回链接。由于某种原因,它错过了所有“更多..”元素的 href 字段中的所有这些 url..

import scrapy
from ..items import CoolBlueItems


class QuoteSpider(scrapy.Spider):
    name = "coolblue2"

    start_urls = ["https://www.coolblue.nl/en/our-assortments]

    def __init__(self):

        self.declare_xpath()

    def declare_xpath(self):

        self.getAllSubCategoriesUrlsXpath = "//a[@class='category-navigation--link']/@href"

    def parse(self, response):

        item = CoolBlueItems()

        urls_list = []

        no_scrape_urls = ["/en/promotion", "/en/second-chance", "/en/gift-cards", "/en/coolblue-fan-products", "/en/all-brands"]

        for Urls in response.xpath(self.getAllSubCategoriesUrlsXpath).getall():

            current_url = Urls.strip()

            if current_url not in urls_list and current_url not in no_scrape_urls and current_url.count("/") == 2:
                urls_list.append(current_url)
                item["Url"] = response.urljoin(current_url)
                yield item

我遵循了 PS1212 的建议。不得不进行一些修改,因为它抛出了与处理信息的方式相关的错误。功能:

import scrapy
from ..items import CoolBlueItems
    
    
    class QuoteSpider(scrapy.Spider):
        name = "coolblue2"
    
        start_urls = ["https://www.coolblue.nl/en/our-assortments]

        for a in response.css("a.category-navigation--link::attr('href')").getall():
            item["Url"] = re.split('/', a)
            yield item

它仍然会跳过我想要的那个元素。以下是输出的第一个条目:

Category,CurrentPrice,OriginalPrice,Title,Url
,,,,",en,laptops"
,,,,",en,laptops,apple-macbook"
,,,,",en,desktops"
,,,,",en,monitors"
,,,,",en,keyboards"

编辑:问题出在选择器本身。我可以让我的脚本工作,但我仍然很好奇为什么 CSS 选择器工作而 xpath 不工作。这是我所做的一个测试,我使用 xpath 和 css 来从“a”部分中抓取具有特定类的所有元素:

>>> response.xpath("//a[@class='category-navigation--link']")[4].getall()
['<a class="category-navigation--link" href="/en/keyboards" rel="nofollow">\n                    Keyboards\n                </a>']
>>>



>>> response.css('a.category-navigation--link')[4].get()
'<a class="category-navigation--link category-navigation--link--black" href="/en/laptops-desktops-monitors" data-trackclickevent="Homepage categor
y navigation|Computers &amp; tablets|More..">\n                                                                        More..\n
                                                 </a>'

如您所见,数组的第 5 个元素(两种情况下的索引 4)返回不同的值。我一定是在我的 Xpath 选择器的某个地方出错了。

【问题讨论】:

  • 向我们展示您正在使用的代码以及您获得的结果。说“它以某种方式无法获取信息”并不能告诉我们太多。

标签: python xpath scrapy


【解决方案1】:

试试这个:

import requests, re
from bs4 import Beatifulsoup

htl = requests.get('https://www.coolblue.nl/en/our-assortment')
soup = Beautifulsoup(htl.text, 'lxml')

a_tages = soup.findAll('a', class_='category-navigation--link')
for a in a_tages:
       href_list = re.split('/',a.get('href')))
       print(href_list.pop())

通过 Scrapy:

import scrapy
from ..items import CoolBlueItems

class QuoteSpider(scrapy.Spider):
      name = "coolblue2"
      start_urls = ["https://www.coolblue.nl/en/our-assortments]

      def parse(self, response):
          item = CoolBlueItems()

          for a in response.css('a.category-navigation--link'):
              url = a.css("::attr('href')").extract()
              split_url = re.split('/', url))
              print(split_url.pop())

输出

laptops
apple-macbook
desktops
monitors
laptops-desktops-monitors
...

【讨论】:

  • PS1212 答案有效,最后一行“laptops-desktops-monitors”是我所缺少的,但我需要通过 scrapy 来完成。
  • 太棒了!它也适用于scrapy。您只需要根据它更改选择器模式。
  • 在 PS1212 帖子中添加了我的代码。我认为它应该像你的那样工作,它只是返回网址。
  • @JumBê 刚刚更新了我对scrapy 代码的答案。希望它能解决您的问题。
  • 发现它的实现存在一些问题,但我设法让它工作。它仍然返回与我的 xpath 示例相同的内容。是因为我做了修改吗?我用我所做的更新了帖子
猜你喜欢
  • 2018-08-05
  • 2020-03-01
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多