如何从元素标签中不存在的 xpath 中提取字段?

How to extract a field from xpath which is not present in an element tag?

<div class="info">
    <span class="label">Establishment year</span>
    "2008"
</div>

我想用xpath提取2008,但是表达式只选择了建立文本。

driver.find_element_by_xpath("//*[text()='Establishment year']")

由于文本 2008 位于 文本节点中 以提取文本 2008 你可以使用以下解决方案:

print(driver.execute_script('return arguments[0].lastChild.textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='info']/span[@class='label' and text()='Establishment year']/..")))).strip())

不幸的是 WebDriver does not allow find_element function result to be a Text Node so you will have to go for execute_script 函数如下:

driver.execute_script(
"return  document.evaluate(\"//div[@class='info']/node()[3]\", document, null, XPathResult.STRING_TYPE, null).stringValue;")

演示:

更多信息: