使用带有python片段的XPath无法获得正确的结果

2024-10-03 13:27:59 发布

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

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

如果您访问这个网站并检查例如元素“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

我需要帮助解决这个问题。谢谢。你知道吗


Tags: importhttp网站链接wwwnllilinks
2条回答

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

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')

试试看

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")

相关问题 更多 >