[英]How to click on this button with Selenium?
这是我尝试根据“检查”单击的元素的所有部分:
<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
::before
<div class="ui-dialog-buttonset">
<button type="button" class="done ui-button ui-corner-all ui-widget">
Done</button>
</div>
::after
</div>
当我想单击它时,我假定它在::before
部分上,因为它显示并可以单击。 在代码中,我确保滚动并等待两秒钟,然后单击以确保该按钮可见,但是我得到了:
selenium.common.exceptions.ElementNotVisibleException: Message: element not interactable
但是我不明白它是如何不可交互的。 当我将鼠标悬停在检查器中时, <button>...</button>
突出显示,因此我要单击的按钮必须位于其中,对吗?
这是我尝试过的几件事:
browser.find_element_by_css_selector('button[type=button]').click()
browser.find_elements_by_xpath("//*[contains(text(), 'Done')]").click()
# The above returns a list for some reason?
browser.find_elements_by_css_selector('done.ui-button.ui-corner-all.ui-widget')
我希望我能记住我所做的一切,但是不管我希望有人能帮助我。
要单击元素,因为所需元素是动态元素,则必须诱使WebDriverWait使该元素可单击,并且可以使用以下解决方案之一:
使用CSS_SELECTOR
:
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.ui-dialog-buttonpane.ui-widget-content.ui-helper-clearfix"))).click()
使用XPATH
:
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='ui-dialog-buttonpane ui-widget-content ui-helper-clearfix']"))).click()
注意 :您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在selenium.common.exceptions.ElementNotVisibleException中找到详细的讨论:消息:元素无法使用Selenium进行交互
您可以使用ActionChains移至元素
from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_elements_by_css_selector("div.ui-dialog-buttonpane.ui-widget-content.ui-helper-clearfix")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
或者您可以使用scrollIntoView()滚动直到元素在视图中:
driver.execute_script("arguments[0].scrollIntoView();", element)
当您使用.find_elements
(请注意复数)时,它将返回列表,而不是像.find_element
(单数)那样的单个元素。 你有没有尝试过
browser.find_element_by_xpath("//button[.='Done']")
如果在这些.find_elements
调用中得到len()
,它是1吗? 我想知道是否有不止一个按钮与您正在使用的定位器匹配,而第一个按钮不可见,但您想要第二个或第三个按钮,依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.