Selenium 點選按鈕

Selenium 可以自動點選網頁上顯示的按鈕。在此示例中,我們將開啟一個站點,然後單擊單選按鈕並提交按鈕。

Selenium 按鈕單擊

開始匯入 selenium 模組並建立 Web 驅動程式物件。然後我們使用該方法:

drivers.find_elements_by_xpath(path)

找到 html 元素。為了獲得路徑,我們可以使用 chrome 開發工具(按 F12)。我們將游標放在 devtools 中並選擇我們感興趣的 html 按鈕。然後將顯示路徑,如示例螢幕截圖所示:

![使用 chrome dev 工具按 xpath 查詢元素](/img/Tutorial/Python Selenium/find_element_by_xpath.webp)

在我們有了 html 物件之後,我們使用 click() 方法進行最終的單擊。

完整程式碼:

from selenium import webdriver
import time
 
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
options.binary_location = "/usr/bin/chromium"
driver = webdriver.Chrome(chrome_options=options)
driver.get('http://codepad.org')
 
# click radio button
python_button = driver.find_elements_by_xpath("//input[@name='lang' and @value='Python']")[0]
python_button.click()
 
# type text
text_area = driver.find_element_by_id('textarea')
text_area.send_keys("print('Hello World')")
 
# click submit button
submit_button = driver.find_elements_by_xpath('//*[@id="editor"]/table/tbody/tr[3]/td/table/tbody/tr/td/div/table/tbody/tr/td[3]/input')[0]
submit_button.click()