如何在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.tw/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.tw/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