gpt4 book ai didi

css - 如何在 Scrapy 中将 CSS 选择器转换为 XPath?

转载 作者:行者123 更新时间:2023-11-28 14:29:19 26 4
gpt4 key购买 nike

我想在 Scrapy 元素中将 CSS 选择器转换为 XPath。

我正在从它的网站教程中学习 Scrapy,但我无法将 CSS 语言直接转换为 XPath。

用于解析 http://quotes.toscrape.com/ 的 CSS 选择器是:

`>>> for quote in response.css("div.quote"):
... text = quote.css("span.text::text").extract_first()
... author = quote.css("small.author::text").extract_first()
... tags = quote.css("div.tags a.tag::text").extract()
... print(dict(text=text, author=author, tags=tags))`

我尝试使用 XPath 编写如下:

In [83]: for quote in response.xpath('//div[@class="quote"]'):
...: text = quote.xpath('//span[@class="text"]/text()').extract_first()
...: author = quote.xpath('//small[@class="author"]/text()').extract_first()
...: tags= quote.xpath('//div[@class="tags"]/a[@class="tag"]/text()').extract()
...: print(dict(text=text,author=author,tags=tags))`

在 CSS 路径中,我获得有关不同引号的信息,而在 XPath 中,我在列表中多次获得相同的引号。我做错了什么?

最佳答案

"In the CSS path I get info on different quotes, while on XPath I get the same quote multiple times in the list. What am I doing wrong?"

主要问题是由于 XPath 将表达式开头的 / 解释为对根文档的引用,与执行表达式的上下文元素无关。您想要通过在开头添加 . 来明确告诉您要在当前上下文元素(变量 quote 引用的元素)上执行表达式,例如:

text = quote.xpath('.//span[@class="text"]/text()').extract_first()

关于css - 如何在 Scrapy 中将 CSS 选择器转换为 XPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54316486/

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