如何使用 Python 中 Selenium 的 Javascript 執行器重新整理瀏覽器並導航到新頁面?


我們可以使用 Selenium 中的 Javascript 執行器重新整理頁面,然後從當前頁面導航到新頁面。Javascript 是一種用於指令碼編寫的語言,並在客戶端(瀏覽器上)執行。Selenium 提供了使用 Javascript 的預設方法。

語法

driver.execute_script('history.go[0]')
javaS = "window.location = 'https://tutorialspoint.tw/index.htm'"
driver. execute_script(javaS)

有兩種使用 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 語句和已識別的 Web 元素作為引數。

語法

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

Javascript 執行器還可以返回值。因此,execute_script() 可以返回值,例如,我們可以使用此概念獲取頁面的標題。

語法

print driver.execute_script('return document.title')

示例

使用 Javascript 進行頁面重新整理和啟動新 URL 的程式碼實現。

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 with Javascript executor
driver.execute_script('history.go[0]')
# to navigate to a new page
javaS = "window.location = 'https://tutorialspoint.tw/index.htm'"
driver. execute_script(javaS)
#to close the browser
driver.close()

更新於:2020-07-28

953 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告