如何使用 Python 中的 Selenium 選中頁面中的複選框?


我們可以在 Selenium 中使用 click() 方法選中頁面中的複選框。首先我們需要使用任何定位器(如css、xpath、id、類等)唯一標識複選框。

接下來,我們必須使用 findElement() 方法找到元素,最後執行點選操作。如果頁面上找不到匹配的元素,將會丟擲異常。

語法

driver.find_element_by_xpath("//input[@name='check-box']")

舉例

複選框選擇程式碼實現。

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/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
# identifying the checkbox with xpath, then click
driver.find_element_by_xpath("//input[@value='Automation Tester']")
.click()
#to close the browser
driver.close()

更新於: 2020 年 7 月 29 日

7 千次 + 瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.