我想要做的只是:轉到「http://news.google.com」並點擊側邊菜單上的「Technology」鏈接。這裏是我的代碼:Python Selenium - 嘗試點擊鏈接時出現'ElementNotVisibleException'錯誤
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的新手,但我相信這不是正常行爲,有人可以確認嗎?如果這是正常的,那麼是否有人可以告訴我如何確保我的測試每次都能正確運行?
僅供參考,'driver.find_element_by_link_text(「技術」 )'不起作用,因爲該頁面在你要求它找到該鏈接時沒有加載。這不是正確的定位策略(頁面上的其他鏈接可能具有「技術」文本),但這就是爲什麼它不起作用。 – sheeptest 2014-09-24 03:09:44