如何在硒Python中单击图标

时间:2020-03-05 19:12:09

标签: python selenium

我正在尝试通过Selenium和python在网页上注销,目前还不走运。为了注销,我需要单击网页右上角的链接,它将打开一个小的下拉窗口,然后单击此下拉列表中的“注销”图标。窗口。这是此下拉窗口的图片。 enter image description here

以及下拉窗口中此注销图标的检查代码。

enter image description here

现在在我的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以外,还有谁知道更好的方法来解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

问题很可能是在单击下拉菜单后,它没有完全展开/呈现。尽管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_locatedpresence_of_element_located

等待

答案 1 :(得分:1)

打开下拉窗口后,单击带有登出文字的图标,您需要为element_to_be_clickable()引入 WebDriverWait ,您可以使用以下任一here

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.portals-separator +table td>a[title='Log out'][data-mkey='Logout']>img"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Support and Settings']//following-sibling::table[1]//td/a[@title='Log out' and @data-mkey='Logout']/img"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC