如何在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()

更新於:2020年7月29日

805 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.