从 Element Selenium Python 打印文本

Posted

技术标签:

【中文标题】从 Element Selenium Python 打印文本【英文标题】:Printing Text from Element Selenium Python 【发布时间】:2021-07-24 16:07:43 【问题描述】:

我想将此部分打印到控制台。 (标记)Image

这是我最后一次尝试:

我在上次尝试时收到此错误:

无法定位元素:

"method":"xpath","selector":"//*[@id="react-root"]/section/main/div/ul/li[2]/a/span"

请保留我的此文本更改。

followers = driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/ul/li[2]/a/span').GetAttribute("innerhtml")

print("Followers: " + followers)

【问题讨论】:

你有什么问题? 如果你有,这能回答吗? How to get text with Selenium WebDriver in Python 文本发生了变化,当我尝试使用 XPath 定位它时却找不到它。 @ZetlexDK 可以分享一下相关的HTML源码吗?或网址 instagram.com/travel.themepage 【参考方案1】:

您可以使用以下 xpath :

//a[contains(@href, 'followers')]/span

Selenium - Python 绑定中没有任何GetAttribute 方法可用。

相反,您可以使用:

followers = driver.find_element_by_xpath("//a[contains(@href, 'followers')]/span").get_attribute("innerHTML")
print("Followers: ", followers)

【讨论】:

【参考方案2】:

你能检查一下吗

followerTxt=driver.find_element_by_xpath("((//a[@class='-nal3 ']/span)[2])")

print("Total followers: ",followerTxt.text)

我根据元素索引检查过

这是我的输出

【讨论】:

嘿,这行得通,但是错了。我有多少我关注,而不是我有多少关注者。 @Zetlex DK 你能检查我更新的答案吗,我包括输出的快照,显示关注者而不是你关注的数量

以上是关于从 Element Selenium Python 打印文本的主要内容,如果未能解决你的问题,请参考以下文章

Selenium python find_element_by_class_name() 从 v 2.2 到 2.21 停止工作——不能使用“复合类名”

从python中的Selenium Webdriver实例获取文本[重复]

Selenium / Python:无法使用任何find_element_by_ *方法查找元素

使用python selenium检索href值

Python+Selenium学习笔记6 - 定位

python selenium--常用函数1