Selenium Python-单击图像链接时出现错误:消息:元素不可见

时间:2018-11-17 06:36:36

标签: python selenium xpath css-selectors webdriverwait

我正在尝试激发onclick事件进行登录,并且下面是html示例

<div id="divAccInfoDefaultLoginButton" style="display:inline">
    <a href="#" onclick="OnClickLogin();return false;" 
        onmouseout="if ( !isInSSOChecking() &amp;&amp; !isInEKBA() &amp;&amp; EnableAccInfo() ) { loadMouseEventImage('pic_login', 'pic_login'); }" 
        onmouseover="if ( !isInSSOChecking() &amp;&amp; !isInEKBA() &amp;&amp; EnableAccInfo() ) { loadMouseEventImage('pic_login', 'pic_login_on'); }">
        <img id="pic_login" border="0" src="./images/btn_login_ch.gif?cv=L3.01R2" title="登入">
    </a>
</div>

我尝试同时单击href或图像,但均失败,显示为 selenium.common.exceptions.ElementNotVisibleException:消息:元素不可见

href = driver.find_element_by_xpath("//div[@id='divAccInfoDefaultLoginButton']//a")
href.click()

img= driver.find_element_by_xpath("//div[@id='divAccInfoDefaultLoginButton']//a//img")
img.click()

刺激点击动作以触发onclick事件的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

添加WebDriverWait(),还需要切换到iframe

loginFrame = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "betSlipFrame")))
driver.switch_to.frame(loginFrame)

# Login box visible click it
href = driver.find_element_by_xpath("//div[@id='divAccInfoDefaultLoginButton']//a")
href.click()

答案 1 :(得分:0)

要单击标题为登录的元素,您需要诱使 WebDriverWait 使所需的元素可点击,并且您可以使用以下解决方案:

  • CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#divAccInfoDefaultLoginButton>a[onclick*='OnClickLogin']>img#pic_login"))).click()
    
  • XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='divAccInfoDefaultLoginButton']/a[contains(@onclick,'OnClickLogin')]/img[@id='pic_login']"))).click()
    
  • 注意:您必须添加以下导入:

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