如何在Python的Selenium中获取webelement的值?
我们可以使用以下列出的方法从Selenium中的webelement获取值:
使用text方法。
这将返回webelement的内部文本。它基本上返回屏幕上可见的文本及其任何子元素。此方法还会删除所有前导和尾随空格。
使用Javascript执行器。
Javascript文档对象模型可以处理页面上的任何元素。Javascript在客户端运行,并在网页上执行操作。Selenium可以使用execute_script()方法执行Javascript脚本。我们可以使用此方法从webelement获取值。
示例
使用text方法的代码实现
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of css
driver. find_element_by_css_selector("input[class='gsc-input']").
send_keys("Selenium")
# print the entered text in the console
print(driver. find_element_by_css_selector("input[class='gsc-input']").
text)
#to close the browser
driver.close()使用Javascript执行器的代码实现。
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of css
driver. find_element_by_css_selector("input[class='gsc-input']").
send_keys("Selenium")
# print the entered text in the console with Javascript executor
print(driver.execute_script(
'return document.getElementsByName("search")[0].value'))
#to close the browser
driver.close()
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP