作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在 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/
我是一名优秀的程序员,十分优秀!