如何通过使用Python的Selenium Webdriver获得这个html中的一些文本值?

2024-06-05 23:58:07 发布

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

如何使用selemiun和python从以下html代码中获取文本值“This text 1”和“This text 2”:

<p>
   <b>Studio:</b>
   <a href="http://www.somelink.com/some_page/">This Text 1</a>
   " | "
   <b>Director:</b> This Text 2
</p>

我试过几种方法:

driver.find_element_by_xpath("//*[contains(text(), 'Director:')]")

但没有得到结果


Tags: 代码text文本comhttphtmlwwwsome
1条回答
网友
1楼 · 发布于 2024-06-05 23:58:07

获取文本This Text 1This Text 2 使用以下选项

要获得This Text 1,请使用以下xpath

print(driver.find_element_by_xpath("//p/b[contains(.,'Studio')]/following::a").text)

使用JavaScript Executor获取This Text 2

element=driver.execute_script('return arguments[0].lastChild.textContent;', driver.find_element_by_xpath("//p[contains(.,'Director')]"))
print(element.strip())

相关问题 更多 >