如何使用Python从Selenium中的文本对象获取文本

6psbrbz9  于 2023-03-30  发布在  Python
关注(0)|答案(2)|浏览(118)

我有这个Span对象,如示例所示。我试图只获取文本,说,Au Sable。然而,当我使用XPath使用selenium并使用.text时,它说无法获取文本,因为它是一个文本对象。

<span class="tooltip-row">
   <span>Building: </span>
   Ausable Hall
</span>

有人能帮我一下怎么获取短信吗?

kjthegm6

kjthegm61#

尝试导航到 span class=“tooltip-row” 元素并调用 getValue(),而不是 getText()。例如,伪代码:

getElement(By.xPath("//span[@class='tooltip-row']").getValue()
dbf7pr2w

dbf7pr2w2#

要使用Python从Selenium中的WebElement对象中提取文本,可以使用text属性。但是,在您提供的示例中,要提取的文本并不直接包含在span元素中。而是包含在tooltip-row元素的子span元素中。
下面是一个示例代码,它应该提取你想要的文本:

# First, you'll need to locate the parent span element
parent_span = driver.find_element("class name", "tooltip-row")

# Then, you can locate the child span element containing the desired text
child_span = parent_span.find_element("xpath", ".//span[contains(text(),'Building')]/following-sibling::span")

# Finally, you can extract the text from the child span element
text = child_span.text

# Print the text to verify that it has been extracted correctly
print(text) # should output 'Ausable Hall'

在这段代码中,我们首先使用父span元素的类名来定位它。然后,我们使用find_element_by_xpath方法来定位包含我们想要提取的文本的子span元素。该方法中使用的XPath表达式选择包含文本“Building”的span元素,然后选择它的下一个兄弟元素(应该是包含所需文本的span)。最后,我们使用text属性从子span元素中提取文本。

相关问题