gpt4 book ai didi

python - response.xpath 和 response.css 有什么区别

转载 作者:太空宇宙 更新时间:2023-11-04 09:43:43 24 4
gpt4 key购买 nike

我尝试使用以下站点学习 response.xpath 和 response.css:http://quotes.toscrape.com/

scrapy shell 'http://quotes.toscrape.com'
for quote in response.css("div.quote"):
title = quote.css("span.text::text").extract()

这只会得到一个值。但是如果我使用 xpath:

scrapy shell 'http://quotes.toscrape.com'
for quote in response.css("div.quote"):
title = quote.xpath('//*[@class="text"]/text()').extract()

它将获得整个页面上所有标题的列表。

有人可以告诉我使用这两种工具有什么不同吗?有些元素我比较喜欢用response.xpath,比如具体的表格内容,following-sibling很容易获取,但是response.css获取不到

最佳答案

有关 XPath 和 CSS 之间差异的一般说明,请参阅 Scrapy docs :

Scrapy comes with its own mechanism for extracting data. They’re called selectors because they “select” certain parts of the HTML document specified either by XPath or CSS expressions.

XPath is a language for selecting nodes in XML documents, which can also be used with HTML. CSS is a language for applying styles to HTML documents. It defines selectors to associate those styles with specific HTML elements.

XPath 提供了比纯 CSS 选择更多的功能(Wikipedia article 提供了一个很好的概述),但代价是更难学习。 Scrapy 在内部将 CSS 选择器转换为 XPath,因此 .css() 函数基本上是 .xpath() 的语法糖,您可以使用您觉得更舒服的任何一个。

关于您的具体示例,我认为问题在于您的 XPath 查询实际上不是相对于前一个选择器(引号 div),而是相对于整个文档。请参阅 "Working with relative XPaths" 中的这句话在 Scrapy 文档中:

Keep in mind that if you are nesting selectors and use an XPath that starts with /, that XPath will be absolute to the document and not relative to the Selector you’re calling it from.

要获得与 CSS 选择器相同的结果,您可以使用类似这样的方法,其中 XPath 查询是相对于引号 div 的:

for quote in response.css('div.quote'):
print(quote.xpath('span[@class="text"]/text()').extract())

注意 XPath 也有 . expression相对于当前节点进行任何查询,但我不确定 Scrapy 是如何实现的(使用 './/*[@class="text"]/text()' 也给出了你想要的结果)。

关于python - response.xpath 和 response.css 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50657129/

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