Python Selenium - 尝试点击链接时出现'ElementNotVisibleException'错误

时间:2014-09-24 02:28:35

标签: python selenium webdriver

我要做的就是:转到“http://news.google.com”,然后点击侧边菜单上的“技术”链接。这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import unittest, time, re

class GoogleTech(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://www.google.com/"
        self.verificationErrors = []
        self.accept_next_alert = True


    def test_googletech(self):
        driver = self.driver
        driver.get("http://news.google.com")
        #driver.find_element_by_xpath("//div[@id='main-wrapper']/div[@id='main-pane']/div[@class='background']/div[@class='centered']/div[@id='nav-menu-wrapper']/div[@class='browse-sidebar']/ul[@id='anchorman-two-browse-nav']/li[@class='nav-item nv-en_us:tc']/a[contains(text(),'Technology')]").click()
        #driver.find_element_by_xpath("//ul[@id='anchorman-two-browse-nav']/li/a[contains(text(),'Technology')]").click()
        #driver.find_element_by_xpath("//ul[@id='anchorman-two-browse-nav']/li[@class='nav-item nv-en_us:tc']/a[contains(text(),'Technology')]").click()
        #driver.find_element_by_xpath("html/body/div[3]/div[1]/div/div/div[2]/div/ul/li[6]/a").click()
        #driver.find_element_by_link_text("Technology").click()
        wait = WebDriverWait(driver, 10)
        link = wait.until(EC.presence_of_element_located((By.XPATH, "//ul[@id='anchorman-two-browse-nav']/li/a[contains(text(),'Technology')]")))
        link.click()
        time.sleep(10)
        ...

我尝试了很多组合(所有注释掉的线条加上更多!),但仍然无法让它发挥作用。我检查以确保我使用的元素确实存在(使用Element Inspector),然后再将其输入代码。但即使是“find_element_by_link_text”也会给我一个NoSuchElementException异常。有人可以告诉我我做错了吗?

更新:在进行进一步测试后,我现在可以更好地了解news.google.com页面何时出现此错误。所以,基本上,包含“技术”链接的侧边菜单设置为可滚动(我相信这个错误只发生,因为链接在可滚动区域)。如果浏览器(运行时Selenium脚本打开)出现错误,则不会显示“技术”链接,即。您必须最大化浏览器或向下滚动才能看到链接。您可以自己测试此错误 - 当测试打开浏览器时,快速调整浏览器窗口的大小,以便不显示“技术”链接,测试将失败。如果您的初始浏览器窗口在首次打开时未显示“技术”链接,则除非您最大化浏览器窗口或快速向下滚动,直到显示“技术”链接,否则它将失败。该错误可以采取两种形式 - 如果您使用wait.until方法,您将获得Timeoutexception。如果您没有使用wait.until方法,您将看到ElementNotVisibleException。我已经在Chrome和Firefox中进行了测试,对于两者,我都看到了这个问题。我是Selenium的新手,但我相信这不是正常行为,有人可以确认一下吗?如果这是正常的,那么有人可以告诉我如何确保我的测试每次都能正确运行吗?

1 个答案:

答案 0 :(得分:2)

我认为您希望将element_to_be_clickable用作ExpectedCondition

这意味着您的驱动程序将继续轮询Selenium,直到它发现该元素为visibleenabled source

尝试以下解决方案

 link = wait.until(EC.element_to_be_clickable((By.XPATH, "//ul[@id='anchorman-two-browse-nav']/li/a[contains(text(),'Technology')]")))

 link.click()
 time.sleep(10)