如何使用 Python 中 Selenium 的 Javascript 執行器獲取網頁標題和 URL?


我們可以使用 Selenium 中的 Javascript 執行器獲取網頁的標題和 URL。Javascript 是一種用於指令碼編寫的語言,並在客戶端(瀏覽器上)執行。Selenium 提供了預設方法來與 Javascript 進行互動。

語法

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

有兩種使用 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/index.htm")
#to refresh the browser
driver.refresh()
# get the title of page in console
print(driver.execute_script('return document.title'))
# get the URL of page in console
print(driver.execute_script('return document.URL'))
#to close the browser
driver.close()

更新於: 2020-07-28

895 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.