[英]How to find a button in selenium?(Python)
我想在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()
但这没有用。
Selenium里面基本上有4种点击方式。
我会用这个 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:如果我们在HTML DOM
中有唯一条目,请检查dev tools
(Google chrome)。
检查步骤:
Press F12 in Chrome
-> go 到element
部分 -> 执行CTRL + F
-> 然后粘贴xpath
并查看你想要的element
是否用1/1
匹配节点突出显示。
像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
object
wait = WebDriverWait(driver, 20)
定位器也可能不是唯一的。
该元素也可以位于 iframe 等内部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.