我在python中使用Selenium来单击对话框中的按钮。我尝试点击“确定”,但它不断出现错误
以下是代码
<div<class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
<div<class="ui-dialog-buttonset">
<button type="button" class="large ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
<span class="ui-button-text">Cancel</span>
</button>
<button type="button" class="orange large ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
<span class="ui-button-text">OK</span>
</button>
</div>
</div>
谢谢:)
答案 0 :(得分:1)
如果DOM中的元素不可见,如css { display: None}
,{opacity: 0}
...等, selenium 将无法 SEE 即使您尝试wait
或time.sleep
,也应该使用execute_script
运行JavaScript来触发所需的事件,如下所示:
driver.execute_script('document.querySelector("span.ui-button-text").click();')
答案 1 :(得分:0)
在尝试点击之前,您应该等待元素准备就绪。使用waitForVisible
或类似方法来实现这一目标
例如,像这样:
element = WebDriverWait(driver, 10).until(
lambda driver : driver.find_element_by_xpath(element_xpath)
)
如果课程保持不变,那么您应该选择element_xpath
的课程。您需要确定的最后一件事是其他属性将按钮指定为准备好了。然后你可以等待特定的参数:
def find(driver):
e = driver.find_element_by_xpath(element_xpath)
if (e.get_attribute(some_attribute)==some_value):
return False
return e
element = WebDriverWait(driver, 10).until(find)
答案 2 :(得分:0)
Two different things can happen here.
• The selector is not explicitly returning the intended element
• Element load issue.
If both cases are true use explicit wait with a correct selector. In terms of selector I like using text bases search in such scenario. Notice I am using xpatth contains to make sure it eliminates any leading or tailing white spaces.
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH , "//span[contains(text(),'OK')]")))
API doc here