gpt4 book ai didi

python - Scrapy/Python/XPath - 如何从数据中提取数据?

转载 作者:太空狗 更新时间:2023-10-30 02:20:00 25 4
gpt4 key购买 nike

我是 Scrapy 的新手,我才刚刚开始研究 XPath。

我正在尝试从 div 中的 html 列表项中提取标题和链接。下面的代码是我认为我会去做的,(通过 id 选择 ul div,然后遍历列表项):

def parse(self, response):
for t in response.xpath('//*[@id="categories"]/ul'):
for x in t.xpath('//li'):
item = TgmItem()
item['title'] = x.xpath('a/text()').extract()
item['link'] = x.xpath('a/@href').extract()
yield item

但我收到了与这次尝试相同的结果:

def parse(self, response):
for x in response.xpath('//li'):
item = TgmItem()
item['title'] = x.xpath('a/text()').extract()
item['link'] = x.xpath('a/@href').extract()
yield item

导出的 csv 文件包含源代码从上到下的 li 数据...

我不是专家,我已经做了很多尝试,如果有人能对此有所了解,我们将不胜感激。

最佳答案

您需要在内部循环中使用的 xpath 表达式以点开头:

for t in response.xpath('//*[@id="categories"]/ul'):
for x in t.xpath('.//li'):

这将使它在当前元素的范围内搜索,而不是整个页面。

查看更多说明 Working with relative XPaths .

关于python - Scrapy/Python/XPath - 如何从数据中提取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25826823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com