如何在 Python 中使用 Selenium 點選連結?
我們可以藉助 Selenium 提供的定位器在頁面上點選連結。連結文字和部分連結文字是通常用於點選連結的定位器。這兩個定位器都使用錨標記內的文字。
-
連結文字:在 Selenium 中,連結文字用於網頁上的超連結,要在網頁上建立超連結,我們可以使用錨標記後跟連結文字。
-
部分連結文字:只有當添加了部分單詞時,我們才能使用部分連結文字,這使得使用者可以更快地檢索。
安裝 Selenium
使用以下命令在你的 Python 環境中安裝 Selenium。
pip install selenium
下載 WebDriver
我們需要一個與瀏覽器匹配的 web 驅動程式,如果你使用的是 Chrome 瀏覽器,請下載 ChromeDriver 並確保將 WebDriver 可執行檔案新增到系統的 PATH 中。
初始化 WebDriver
使用以下程式碼,我們可以匯入所需的模組並初始化 webdriver。將示例路徑 '/path/to/chromedriver' 替換為你係統上 ChromeDriver 可執行檔案的實際路徑。
from selenium import webdriver # Initializing WebDriver driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
開啟網頁
使用 'get' 方法,我們可以導航到包含你想要點選的連結的網頁。將 'https://www.Example.com' 替換為你的連結所在的頁面的 URL。
# Open the webpage driver.get('https://www.Example.com')
使用連結文字點選連結
利用 Selenium 中提供的定位器,我們可以使用其文字、ID、名稱、類、CSS 選擇器或 XPath 來定位連結。連結文字定位器用於透過匹配錨標記內完全可見的文字定位連結。
driver.find_element_by_link_text("Link Text").click()
示例
在下面的示例程式碼中,driver.maximize_window() 函式最大化瀏覽器視窗。find_element_by_link_text("Company") 函式將使用其精確文字查詢頁面上的超連結。
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://www.Example.com") # To refresh the browser driver.refresh() # Identifying the link with the help of link text locator driver.find_element_by_link_text("Company").click() # To close the browser driver.close()
使用部分連結文字點選連結
部分連結文字定位器匹配任何在錨標記內部分包含指定文字字串的連結。
driver.find_element_by_partial_link_text("Partial Link Text").click()NoSuchElementException shall be thrown for both these locators if there is no matching element.
如果不存在匹配的元素,則這兩個定位器都會丟擲 NoSuchElementException。
示例
在下面的示例程式碼中,find_element_by_partial_link_text("Privacy") 函式查詢文字包含單詞 "Privacy" 的連結,並且不需要匹配連結的全文。
from selenium import webdriver # Browser exposes an executable file 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() # Identifying the link with the help of partial link text locator driver.find_element_by_partial_link_text("Privacy").click() # To close the browser driver.quit()