【问题标题】:Not getting the right result using XPath with python scraper使用带有 python 刮板的 XPath 没有得到正确的结果
【发布时间】:2015-10-09 20:33:23
【问题描述】:

我正在尝试使用 python Scraper 获取一些特定网站的一些信息,即一些产品的链接。我正在查看的网站是http://www.ah.nl/producten/verse-kant-en-klaar-maaltijden-salades 我正在寻找的链接如下

如果访问该网站并检查例如元素“Maaltijdsalades”,那么您可以使用 XPath 语法看到链接位于 //ul/li 下。问题是在同一个 HTML 代码中,还有一个地方 //ul/li 用于我不寻找的链接。我使用了下面的蜘蛛,它准确地抓取了我不想要的链接。

我正在使用以下蜘蛛

import scrapy

from ah_links.items import AhLinksItem

class AhSpider(scrapy.Spider):
    name = "ah_links"
    allowed_domains = ["ah.nl"]
    start_urls=['http://www.ah.nl/producten/aardappel-groente-fruit', 
    ]

def parse(self, response):
    for sel in response.xpath('//ul/li'):
        item = AhLinksItem()
        item['title'] = sel.xpath('a/@href').extract()
        yield item

我需要帮助来解决这个问题。谢谢。

【问题讨论】:

    标签: python html xpath web-scraping scrapy


    【解决方案1】:

    据我了解,您应该在子类别块中搜索列表:

    for sel in response.css('nav.subcategorynav li'):
        item = AhLinksItem()
        item['title'] = sel.xpath('.//a/@href').extract()
        yield item
    

    这里我使用的是 CSS 选择器,但您也可以使用 XPath 来解决它:

    response.xpath('//nav[contains(@class, "subcategorynav")]//li')
    

    【讨论】:

    • 我正在寻找的链接确实在 //nav[@class="subcategorynav"] 下。如果我使用这个 XPath(或 CSS 选择器),我不会得到任何结果。你知道为什么吗?
    • @Badshah 得到它,调试了一下并更新了答案。应该可以,试试看。
    • 它与 CSS 选择器一起工作!谢谢,但它不适用于 XPath...
    【解决方案2】:

    试试

    item['title'] = sel.xpath("./a/@href").extract()
    

    已编辑,按预期工作

    import requests
    from lxml.html import fromstring
    response = requests.get("http://www.ah.nl/producten/aardappel-groente-fruit")
    parsed_response = fromstring(response.text)
    for item in parsed_response.xpath(".//ul/li"):
        print item.xpath("a/@href")
    

    【讨论】:

    • 我试过了,但也没有用。如果我可以问,为什么这一点会有所帮助?
    猜你喜欢
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2014-11-16
    • 2023-03-15
    相关资源
    最近更新 更多