我想在 selenium 中找到這個按鈕:
<input class="button button-primary" type="submit" value="Send me the code" data-type="save">
我試過這個:
driver.find_element_by_xpath("//input[@value='Send me the code']").click()
但這沒有用。
uj5u.com熱心網友回復:
基本上有 4 種方法可以在 Selenium 中單擊。
我將使用這個 xpath
//input[@value='Send me the code']
代碼試用1:
time.sleep(5)
driver.find_element_by_xpath("//input[@value='Send me the code']").click()
代碼試用2:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@value='Send me the code']"))).click()
代碼試用3:
time.sleep(5)
button = driver.find_element_by_xpath("//input[@value='Send me the code']")
driver.execute_script("arguments[0].click();", button)
代碼試用4:
time.sleep(5)
button = driver.find_element_by_xpath("//input[@value='Send me the code']")
ActionChains(driver).move_to_element(button).click().perform()
進口:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
PS:請檢查dev tools(谷歌瀏覽器)我們是否有唯一的條目HTML DOM。
檢查步驟:
Press F12 in Chrome- >去element節- >做一個CTRL F- >再貼上xpath看看,如果你需要的element是越來越強調與1/1匹配的節點。
uj5u.com熱心網友回復:
像這樣的簡單代碼行driver.find_element_by_xpath("//input[@value='Send me the code']").click()可能無法正常作業的原因有很多。
最可能的原因可能是錯過了等待/延遲。您應該等到元素完全加載后再嘗試訪問它。而不是使用driver.find_element_by_xpath("//input[@value='Send me the code']").click()請嘗試這樣的事情:
wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@value='Send me the code']"))).click()
要使用它,您將需要以下匯入:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
并初始化wait物件
wait = WebDriverWait(driver, 20)
定位器也可能不是唯一的。
該元素也可以位于 iframe 等內部。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/315545.html
