我正在尝试通过selenium和python在网页上注销,目前还不走运。为了注销,我需要单击网页右上角的链接,它将打开一个小的下拉窗口,然后单击该下拉菜单中的“注销”图标。窗口。这是此下拉窗口的图片。
以及下拉窗口中此注销图标的检查代码。
现在,在我的python代码中,我能够打开下拉窗口,但是如果我单击注销图标,我将不断收到“ selenium.common.exceptions.ElementNotVisibleException”的异常。
这是我的代码:
try:
# to click the link so that the drop-down window opens
action = ActionChains(self.driver)
dropdownwindow= self.driver.find_element_by_xpath("//span[@class='ssobanner_logged']/img")
action.move_to_element(dropdownwindow).perform()
dropdownwindow.click()
# try to click the logout icon in the drop-down so that user may logout
logoutLink = self.driver.find_element_by_xpath(
"//*[@id='ctl00_HeaderAfterLogin1_DL_Portals1']/tbody/tr/td[4]/a/img")
action.move_to_element(logoutLink).perform()
logoutLink.click()
return True
except Exception as e:
self.logger.info(e)
raise
return False
而且我在运行时遇到了这样的异常。
selenium.common.exceptions.NoSuchElementException:
Message: no such element: Unable to locate element:
{"method":"xpath","selector":"//*[@id='ctl00_HeaderAfterLogin1_DL_Portals1']/tbody/tr/td[4]/a/img"}
除了我使用的xpath以外,没有人知道更好的处理方法吗?
最有可能是单击下拉菜单后,下拉菜单没有完全展开/呈现。尽管time.sleep(1)
命令可能是一个潜在的解决方法,但更合适的解决方法是使用WebDriverWait
的动态等待:
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
by = By.XPATH # This could also be By.CSS_SELECTOR, By.Name, etc.
hook = "//*[@id='ctl00_HeaderAfterLogin1_DL_Portals1']/tbody/tr/td[4]/a/img"
max_time_to_wait = 10 # Maximum time to wait for the element to be present
WebDriverWait(driver, max_time_to_wait).until(expected_conditions.element_to_be_clickable((by, hook)))
[expected_conditions
也可以使用visibility_of_element_located
或presence_of_element_located
]等待>