2016-02-13 91 views
0

硒有沒有辦法確定click()函數是否正確執行?如何捕捉點擊()失敗?

假設一個網頁有一個帶有提交按鈕的表單。我使用硒來點擊提交按鈕。我如何確定click()是否正確發生?現在我的代碼看起來像這樣:

try: 
    button = driver.find_element_by_id('submit_button_id') 
    button.click() 
except NoSuchElementException: 
    print('No such button found.') 

# determine if the `click()` function actually worked. 
try: 
    driver.find_element_by_id(
    'new_id_that_only_occurs_after_button_click' 
) 
except NoSuchElementException: 
    # code to retry button click 

有沒有更好的方法?

回答

1

沒有什麼比檢查點擊頁面上的變化更符合你的期望了。所以你在做什麼是對的。我會做的唯一的改進是改變「找」到「等待」,像in the example shown here

WebDriverWait(driver, 10) 
    .until(
     EC.presence_of_element_located(
      (By.ID, 
      'new_id_that_only_occurs_after_button_click')) 

這樣的測試更可靠(如果響應單擊操作需要一點時間,測試將不失敗)。