如何在Selenium Python execute_script中获取返回元素的值

How to get value of returned element in Selenium Python execute_script?

本文关键字:获取 返回 元素 script Selenium Python execute      更新时间:2023-09-26

I使用SeleniumPython绑定来查找一些元素。在某些地方,我需要使用executescript方法。执行此脚本时返回的值很热吗?

所以我放了:

browser = driver.Chrome() #for example
script = "document.getElementById('element')"
browser.execute_script(script)

如何从该脚本将值接收到python日志或变量中?像元素的ID、文本等。?

我遇到了一个问题,selenium找不到一些元素,但chrome上的JavaScript控制台找到了它。

因此,我尝试在execute脚本方法中添加一个"return"字符串,在您的情况下是:

browser = driver.Chrome()
myElement = browser.execute_script("return document.getElementById('element_id')")

您还可以像使用SeleniumWeb元素那样执行不同的操作。

示例:

browser = driver.Chrome()
elementList = browser.execute_script("return document.getElementsByClassName('element_class_name')")
elementList[0].click() # Clicks the first element from list

我希望这能有所帮助!

从js-doc(可以在那里找到python api)

如果脚本具有返回值(即,如果脚本包含return语句),则将对解析此函数返回值:-对于HTML元素,该值将解析为网络驱动程序。WebElement-Null和未定义的返回值将解析为Null
-布尔值、数字和字符串将按原样解析函数将解析为他们的字符串表示-对于数组和对象,每个成员项将根据上述规则进行转换

附言:为什么需要使用executeScript查找元素?