在 Selenium 中使用 python 有哪些提交表單的方式?


在 Selenium 中有多種提交表單的方式。一種方法是直接在表單提交按鈕上使用 click() 方法。另一種方法是在表單頁面上使用 submit() 方法。

  • 使用 submit() 方法。

    在表單頁面上輸入所需資料後,此方法將簡單地提交該表單。

語法

driver.find_element_by_xpath("//input[class ='gsc-search']").submit()
  • 使用 click() 方法。

    在表單頁面上輸入所需資料後,此方法將單擊表單的提交按鈕。

語法

driver.find_element_by_xpath("//button[id ='value']").click()

舉例

使用 submit() 方法進行的程式碼實現。

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/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of id and enter text
driver.find_element_by_id("gsc-i-id1").send_keys("Selenium")
# submit the text contents
driver.find_element_by_id("gsc-i-id1").submit()
#to close the browser
driver.close()

使用 click() 方法進行表單提交的程式碼實現。

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/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of id and enter text
driver.find_element_by_id("gsc-i-id1").send_keys("Selenium")
# identifying the button then using click() method
driver.find_element_by_xpath("//button[contains(@class,'gsc-search')]") .click()
#to close the browser
driver.close()

更新日期: 2020 年 7 月 29 日

6K+ 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告