python - 用硒填充网络表单,如何单击仅在某些条件下启用的按钮
问题描述
我正在尝试使用 selenium 和 python 自动填写本网站中的表格: https ://breast.predict.nhs.uk/tool 我可以填写除“仅微转移”之外的所有框。如果我尝试以我填写其他内容的方式单击此选项,即:
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
elem = driver.find_element_by_xpath("//*[@id=\"app\"]/div/div/div[3]/div/div/div/div/div[2]/form/div[4]/div[2]/div/div/div[3]/div/div/div/div/button[1]")
elem.click()
我收到以下错误:
selenium.common.exceptions.NoSuchElementException: Message: no such element:
Unable to locate element: {"method":"xpath","selector":"//*[@id="app"]/div/div/div[3]
/div/div/div/div/div[2]/form/div[4]/div[2]/div/div/div[3]/div/div/div/div/button[1]"}
我相信这是因为微转移按钮仅在正节点 = 1 时才可用。
为了尝试解决这个问题,我通过以下方式查看了使用显式等待:
element = WebDriverWait(driver, 20).until(ec.element_to_be_clickable((By.XPATH, "//*[@id=\"app\"]/div/div/div[3]/div/div/div/div/div[2]/form/div[4]/div[2]/div/div/div[3]/div/div/div/div/button[1]")))
element.click()
这会输出以下错误:
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
单击此按钮的正确方法是什么?任何帮助表示赞赏。
谢谢!
解决方案
使用WebDriverWait
and element_to_be_clickable
() 和以下xpath
选项。
driver.get("https://breast.predict.nhs.uk/tool")
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.ID,"nodes"))).send_keys('1')
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//button[@class='btn btn-default btn-sm custom' and text()='Yes']"))).click()