XPATH在网页上找不到包含文本的文字 - 使用contains(text())

2024-10-06 11:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在这个网站上https://classicdb.ch/?quest=788

我试过:

driver.find_element_by_xpath(
                "//div[contains(text(), 'Start')]").text

它找到元素并返回

'Start: Kaltunk'

但是,当我试图找到包含“End”的元素时,它什么也找不到。你知道吗

driver.find_element_by_xpath(
                "//div[contains(text(), 'End')]").text

为什么会这样?你知道吗

谢谢你。你知道吗


Tags: texthttpsdiv元素by网站driverelement
1条回答
网友
1楼 · 发布于 2024-10-06 11:26:19

尝试使用下面的xpath。你知道吗

//table//div[contains(.,'End:')]

屏幕截图:

enter image description here

说明:编辑1

首先,让我们看看目标div下有多少text()节点。你知道吗

enter image description here

因此div有3个文本节点。你知道吗

让我详细说明OP使用的原始xpath

//div[contains(text(), 'End')]
 ^div present anywhere in the document
     ^which contains
               ^the **first** text() node with string value as `End`

contains()作为它的第一个参数(在div[argument]中)时,它接受第一个节点的字符串值,但是End出现在第二个文本节点中,而不是第一个。这就是xpath不起作用的原因。你知道吗

我们有两个选择来处理这个问题。你知道吗

1)使用text()作为第一个参数-通过这种方式,它将获得当前上下文下的所有文本节点,然后使用contains()作为条件来检查text()值,该值将匹配值包含End的任何text()节点,如下所示。你知道吗

//div[text()[contains(., 'End')]]
^div present any where in the document
     ^which have text() node
             ^ that contains 'End`

查看以下屏幕截图:

enter image description here

这时,您会有一个问题,为什么OP使用的第一个xpath(//div[contains(text(), 'Start')])有效?你知道吗

如果查看div中关联的text()节点,Starttext出现在第一个text()节点中,这就是他能够使用该xpath的原因。你知道吗

enter image description here

2)使用。要简单地签入当前节点上下文,当您说.时,它将在整个当前元素上下文中签入End。你知道吗

//div[contains(.,'End')]

如果您不将scopt限制为//table(在xpath的开头),那么您将得到5个div作为原始div的祖先div,其中的文本也与xpath匹配。所以在表中限制要检查的范围 `//表//div[包含(,'End')]

相关问题 更多 >