想了解如何解决python中.element_to_be_clickable函数中的“或”语句的问题。如果其中一个元素是可点击的,我希望我的脚本单击其中一个(元素)按钮(我想用完整的xpath在这个方法中列出它们)。目前,它只适用于一个button(/html/body/button[1]
)。有人能帮我吗?
while True:
try:
button = WebDriverWait(window, timeout=(random.randint(5, 10)), poll_frequency=0.2).until(EC.element_to_be_clickable((By.XPATH, "/html/body/button[1]"))).click()
break # leave while loop
except TimeoutException:
window.refresh()
尝试过,但没有成功:
while True:
try:
button = WebDriverWait(window, timeout=(random.randint(5, 10)), poll_frequency=0.2).until(EC.element_to_be_clickable((By.XPATH, "/html/body/button[1]" or "/html/body/button[2]"))).click()
break # leave while loop
except TimeoutException:
window.refresh()
谢谢你的回答!
发布于 2022-10-25 11:36:35
根据文件:
An expectation that any of multiple expected conditions is true.
Equivalent to a logical 'OR'.
Returns results of the first matching condition, or False if none do.
它的使用示例如下:
WebDriverWait(driver, 20).until(
EC.any_of(
EC.element_to_be_clickable((By.XPATH, "/html/body/button[1]")),
EC.element_to_be_clickable((By.XPATH, "/html/body/button[2]"))
)
)
UPD
如果我正确理解了上面链接的文档,上面的代码块将返回一个布尔值,而不是一个web元素对象。所以,你不能直接点击它。要执行单击,我建议使用以下代码:
if WebDriverWait(driver, 20).until(EC.any_of(EC.element_to_be_clickable((By.XPATH, "/html/body/button[1]")), EC.element_to_be_clickable((By.XPATH, "/html/body/button[2]")))):
try:
driver.find_element(By.XPATH, "/html/body/button[1]").click()
except:
driver.find_element(By.XPATH, "/html/body/button[2]").click()
解释:
如果函数返回if
,代码流将进入True
块。这意味着至少找到了一个可点击的元素。
所以,我们可以尝试点击第一个元素。
如果它是可点击的-点击将完成。
否则,将单击第二个元素。
https://stackoverflow.com/questions/74193372
复制相似问题