如何在Selenium Python中获取元素的文本值?

2024-05-16 17:53:53 发布

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

这是我第一次使用硒。我试图获得这两个元素的文本值: element1

element 2

我通过h3标签得到了第一个元素。现在,这两个元素都没有出现。我无法通过任何使用ID的东西进行定位,因为它变化很大

有什么帮助吗

Update@Chikabala:当.text在print语句中时,它将显示输出

Traceback (most recent call last):
  File "C:\Users\re123el\Py5123s\create\try.py", line 42, in <module>
    print(elementList.text)
AttributeError: 'list' object has no attribute 'text'

这是将.text添加到xpath末尾时的输出:

vscGnRMlqsD8rQ
Traceback (most recent call last):
  File "C:\Users\rebel\PycharmProjects\create\try.py", line 40, in <module>
    elementList = sheto.find_elements_by_tag_name("td")
AttributeError: 'str' object has no attribute 'find_elements_by_tag_name'

更新#2: 这是原始代码:

keto = browser.find_elements_by_tag_name("h3")[1].text
print(keto)
sheto = browser.find_element_by_xpath("//table[@class='preftable']/tbody/tr/td[@class='prefright']").text
print(sheto)

这是原始输出:

C:\Users\rebel\PycharmProjects\create\venv\Scripts\python.exe C:/Users/rebel/PycharmProjects/create/try.py
GWrS4IyFkO-bfw


Process finished with exit code 0

域是:https://www.reddit.com/prefs/apps 状态:已登录、已创建应用程序、脚本 需要元素:应用程序id(h3标签)和机密(机密旁边的api,可在td标签中找到)


Tags: textpy元素bycreate标签elementsfind
3条回答

假设您需要第一个tr标记中的文本。 请尝试以下xpath:

driver.find_element_by_xpath(".//table[@class='preftable']/tbody/tr[1]/td[@class='prefright']").text

更新:

driver.find_element_by_xpath(".//table[@class='preftable']/tbody/tr/th[text()='secret']//following::td[1]").text

您可以像这样使用find_elements_by_

sheto = browser.find_element_by_xpath(".//table[@class='preftable']/tbody/tr[1]/td[@class='prefright']")

elementList = sheto.find_elements_by_tag_name("td")

print(elementList.text )

sheto包含第一个元素,elementList包含它的子元素

如果sheto包含多个元素,则可以使用:

for shetos in sheto:
     elementList = shetos.find_elements_by_tag_name("td")
     print(elementList.text )

相关问题 更多 >