如何在Selenium結合Python使用Javascript執行器在輸入文字框中鍵入值?


我們可以使用Selenium中的Javascript執行器在輸入文字框中鍵入值。Javascript是一種用於指令碼編寫的語言,在客戶端(瀏覽器上)執行。Selenium提供了使用Javascript的預設方法。

語法

javaScript = "document.getElementsByClassName('gsc-input')[0].value = 'T' ")
driver.execute_script(javaScript)

有幾種方法可以在瀏覽器中執行Javascript:

  • 在文件根級別執行Javascript。

    在這個過程中,我們將使用定位器(類或ID)識別元素,然後對其執行所需的操作。然後呼叫`execute_script()`方法,並將Javascript作為字串傳遞給它。

語法

javas = "document.getElementsByName('user-search')[0].click();"
driver.execute_script(javas)

請注意,我們使用了`getElementsByName('user-search')[0]`。像`getElementsByName`和`getElementsById`這樣的函式返回匹配元素的陣列。因此,為了定位第一個元素,使用了索引[0]。但是,如果我們使用`getElementById`函式,則不需要使用索引,因為那裡只引用一個匹配的元素。

最後,對於執行,WebDriver將把Javascript語句放入瀏覽器,然後執行必要的動作,例如點選所需的元素。這個Javascript不會與網頁中現有的Javascript混淆。

  • 在元素級別執行Javascript。

    在這個過程中,我們將藉助WebDriver方法(如`find_element_by_xpath`或`find_element_by_id`等)來識別元素。然後對其執行必要的操作,例如點選元素。最後,呼叫`execute_script()`方法。此方法具有Javascript語句和已識別的WebElement作為引數。

語法

userN= driver.find_element_by_id("user-search']")
driver.execute_script("arguments[0].click();", userN)

示例

使用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/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# inputting values in the text box with help of Javascript executor
javaScript = "document.getElementsByClassName('gsc-input')[0].value = 'TestNG' "
driver.execute_script(javaScript)
#to close the browser
driver.quit()

更新於:2020年7月29日

2K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告