如何在selenium python中单击图标

2024-09-30 08:16:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用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之外,还有谁知道更好的处理方法吗


Tags: theto代码self网页imgdriverselenium
2条回答

一旦下拉窗口打开并单击文本为“注销”的图标,您需要为element_to_be_clickable()导入WebDriverWait,您可以使用以下任一Locator Strategies

  • 使用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
    

问题很可能是单击下拉菜单后,下拉菜单未完全展开/呈现。虽然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等待

相关问题 更多 >

    热门问题