2016-12-17 41 views
1

我在使用guide來學習使用python進行TDD。在some point,做遷移後,命令python3 functional_tests.py的輸出應該是(根據書):Selenium無法訪問死對象/元素引用已過時

self.fail('Finish the test!') 
AssertionError: Finish the test! 

但我得到的錯誤:

selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "tr" is invalid: TypeError: can't access dead object 

,並試圖第二次(或更多)的時間後:

selenium.common.exceptions.StaleElementReferenceException: Message: The element reference is stale. Either the element is no longer attached to the DOM or the page has been refreshed. 

我一直在谷歌搜索和搜索類似的問題,但沒有找到一個可以幫助我解決問題。
我正在使用geckodriver,並將其添加到PATH的路徑中。

Django==1.8.7 
selenium==3.0.2 
Mozilla Firefox 50.0.2 
(X)Ubuntu 16.04 

我應該切換到Chrome嗎?這不是微不足道的,它需要我一段時間,但它可以工作嗎?更像Firefox還是Selenium?我不認爲它是代碼相關的 - 我克隆了repo for chapter 5並且同樣的崩潰正在發生。

+0

恕我直言,對Chrome的支持看起來好多了。這是一種微不足道的,通過apt(對不起剛纔debian cmds /名字)和鉻符號鏈接到/ usr/bin/chrome並且你完成了(關於轉換爲鉻),通過apt來獲得chromedriver和chromium。 –

回答

2

錯誤的產生是因爲前面章節我們POST請求後添加重定向。該頁面暫時刷新,可以搞砸硒。如果你想堅持使用Selenium 3,我在這本書的博客上發現了一個修正:http://www.obeythetestinggoat.com/how-to-get-selenium-to-wait-for-page-load-after-a-click.html

基本上,您可以在NewVisitorTest類中添加一個方法,讓您等待頁面重新加載,然後繼續進行斷言測試。

... 
from contextlib import contextmanager 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support.expected_conditions import staleness_of 

class NewVisitorTest(unittest.TestCase): 
    ... 
    @contextmanager 
    def wait_for_page_load(self, timeout=30): 
     old_page = self.browser.find_element_by_tag_name("html") 
     yield WebDriverWait(self.browser, timeout).until(
      staleness_of(old_page) 
     ) 
    ... 
    def test_can_start_list_and_retrieve_it_later(self): 
     ... 
     inputbox.send_keys("Buy peacock feathers") 
     inputbox.send_keys(Keys.ENTER) 

     with self.wait_for_page_load(timeout=10): 
      self.check_for_row_in_list_table("1: Buy peacock feathers") 

     inputbox = self.browser.find_element_by_id("id_new_item") 
     inputbox.send_keys("Use peacock feathers to make a fly") 
     inputbox.send_keys(Keys.ENTER) 

     with self.wait_for_page_load(timeout=10): 
      self.check_for_row_in_list_table("1: Buy peacock feathers") 
      self.check_for_row_in_list_table("2: Use peacock feathers to make a fly")