使用 Selenium 和 Python 點選超連結按鈕?


我們可以在 Selenium webdriver 中透過 href 連結點選一個連結/按鈕。這可以透過多種方式實現。我們可以使用 find_element_by_link_text() 和 find_element_by_partial_link_text() 方法來執行此任務。

find_element_by_link_text() 方法用於識別元素,其中文字與方法引數中指定的錨標籤中的文字相同。如果沒有匹配的文字,則丟擲 NoSuchElementException。

語法

find_element_by_link_text("Coding Ground")

find_element_by_partial_link_text() 方法用於透過部分匹配方法引數中指定的錨標籤中的文字來識別元素。如果沒有匹配的文字,則丟擲 NoSuchElementException。

語法 −

find_element_by_partial_link_text("Coding")

示例

使用 find_element_by_link_text() 的程式碼實現。

from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
# implicit wait for 5 seconds
driver.implicitly_wait(5)
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://tutorialspoint.tw/about/about_careers.htm")
# identify element with link text and click()
l=driver.find_element_by_link_text("Privacy Policy")
l.click()
driver.quit()

示例

使用 find_element_by_partial_link_text() 的程式碼實現。

from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
# implicit wait for 5 seconds
driver.implicitly_wait(5)
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://tutorialspoint.tw/about/about_careers.htm")
# identify element with partial link text and click()
l=driver.find_element_by_partial_link_text("Privacy")
l.click()
driver.quit()

更新於:28-Aug-2020

8K+ 瀏覽

開啟您的 職業

完成課程即可獲得認證

開始
廣告