我想选择跨度后的 div 内的文本。
来源如下:
<div id="citation">
<cite>Journal</cite>
", "
<span class="year">2014</span>
", "
<span class="volume">100</span>
" (4), pp 100-200"
</div>
我只想要“(4),第 100-200 页”。
我知道如何从整个 div 或每个范围中获取文本,但如何仅获取最后一个文本?这个 XPATH 将不起作用。 ISSUE_XPATH = "//*[@id=\"引用\"]/text()[3]"
并显示此错误消息:
selenium.common.exceptions.InvalidSelectorException:消息:{“errorMessage”:“xpath 表达式的结果\”//*[@id=\“引用\”]/text()[3]\”是:[object Text]。它应该是一个元素。”
最佳答案
不幸的是,//*[@id=\"itation\"]/text()[3]
在 selenium 中不起作用 - 你只能定位实际元素,而不是文本节点.
在这种情况下我要做的是另外使用 BeautifulSoup
HTML 解析器将有助于在带有 class="volume"
的 span
元素之后找到特定的同级文本:
from bs4 import BeautifulSoup
citation = driver.find_element_by_id("citation")
html = citation.get_attribute("outerHTML")
soup = BeautifulSoup(html, "html.parser")
desired_text = soup.find("span", class_="volume").next_sibling
print(desired_text)
关于Python Selenium 如何从跨度后的 div 中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36454693/