温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Can't parse a certain information from some html elements using xpath
css-selectors python python-3.x scrapy xpath

python - 无法使用xpath解析某些html元素中的某些信息

发布于 2020-03-27 10:56:27

我创建了一个xpath表达式来定位元素,以便可以在scrapy中使用xpath从某些html元素中提取某些信息。无论如何我都无法达到。

HTML元素:

<div class="rates">
                <label>
                  Rates :
                </label>
                  R 3500
                  <br class="hidden-md hidden-lg">
              </div>

我希望从中提取R 3500出来。

我尝试过:

from scrapy import Selector

html = """
<div class="rates">
                <label>
                  Rates :
                </label>
                  R 3500
                  <br class="hidden-md hidden-lg">
              </div>
"""
sel = Selector(text=html)
rate = sel.xpath("//*[@class='rates']/label/following::*").get()
print(rate)

运行上面的脚本后,这就是我想要的,<br class="hidden-md hidden-lg">而我希望得到R 3500

.tail如果选择我可以使用lxml但是,当我抓狂时,找不到任何类似的东西。

如何使用xpath从html元素中提取该比率?

查看更多

查看更多

提问者
MITHU
被浏览
194
RomanPerekhrest 2019-07-03 22:55

要将文本节点作为节点following-sibling之后的label节点:

...
sel = Selector(text=html)
rate = sel.xpath("//*[@class='rates']/label/following-sibling::text()").get().strip()
print(rate)

输出:

R 3500

另外"//*[@class='rates']/label/following::text()"应该也可以。

https://www.w3.org/TR/1999/REC-xpath-19991116#axes