如何在 Python 的 Selenium 中選擇頁面中的單選按鈕?


我們可以藉助 click() 方法在 Selenium 中選擇頁面中的單選按鈕。首先我們需使用 css、xpath、id、class 等任何型別的定位器來唯一地識別該複選框。

接下來,我們必須使用 findElement() 方法來定位該元素,最後執行點選操作。如果在頁面中找不到匹配的元素,則會引發異常。

語法

driver.find_element_by_xpath("//input[@name='radio-button']")

示例

單選按鈕選擇的程式碼實現。

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 radio button with xpath then click
driver.find_element_by_xpath("//input[@value='Female']").click()
#to close the browser
driver.close()

更新日期:2020 年 7 月 29 日

5,000+ 次瀏覽

啟動你的 職業

透過完成課程獲得認證

開始
廣告