Python Selenium陈旧元素异常

时间:2015-08-22 16:56:30

标签: python django selenium

我研究Django和TDD。有代码(功能测试),用于验证输入表格位于中心。

from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class NewVisitorTest(LiveServerTestCase):
"""
Test Class
"""
def setUp(self):
    self.browser = webdriver.Chrome()
    self.browser.implicitly_wait(3)

def tearDown(self):
    self.browser.quit()

def test_layout_and_styling(self):
    self.browser.get(self.live_server_url)
    self.browser.set_window_size(1024, 768)

    inputbox = self.browser.find_element_by_id('id_new_item')
    self.assertAlmostEqual(
        inputbox.location['x'] + inputbox.size['width'] / 2,
        512, delta=10
    )

    inputbox.send_keys('testing\n')
    inputbox = self.browser.find_element_by_id('id_new_item')
    self.assertAlmostEqual(
        inputbox.location['x'] + inputbox.size['width'] / 2,
        512, delta=10
    )

发生错误:

======================================================================
ERROR: test_layout_and_styling (functional_tests.tests.NewVisitorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
   File "e:\Education\ttd\superlists\functional_tests\tests.py", line 112, in tes
t_layout_and_styling
inputbox.location['x'] + inputbox.size['width'] / 2,
  File "c:\Program Files\Python34\lib\site-packages\selenium\webdriver\remote\we
belement.py", line 358, in location
old_loc = self._execute(Command.GET_ELEMENT_LOCATION)['value']
  File "c:\Program Files\Python34\lib\site-packages\selenium\webdriver\remote\we
belement.py", line 448, in _execute
return self._parent.execute(command, params)
  File "c:\Program Files\Python34\lib\site-packages\selenium\webdriver\remote\we
bdriver.py", line 196, in execute
self.error_handler.check_response(response)
  File "c:\Program Files\Python34\lib\site-packages\selenium\webdriver\remote\er
rorhandler.py", line 181, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale elemen
t reference: element is not attached to the page document
  (Session info: chrome=44.0.2403.155)
  (Driver info: chromedriver=2.18.343845 (73dd713ba7fbfb73cbb514e62641d8c96a9468
2a),platform=Windows NT 6.1 SP1 x86_64)

使用Firefox可以正常工作。 我也试过了:

from selenium.webdriver.support.ui import WebDriverWait
...
...
def find(driver):
    element = driver.find_elements_by_id("data")
    if element:
        return element
    else:
        return False
element = WebDriverWait(driver, secs).until(find)

另外,我试过:self.browser.implicitly_wait(3),但它没有帮助。我有Selenium和ChromeDriver的最新更新。请告知它有什么问题?

我在stackoverflow上阅读了类似的问题,但它也无济于事。 谢谢!

1 个答案:

答案 0 :(得分:1)

inputbox.send_keys( '测试\ N')

我想打赌你的表单正在回复换行符并提交自己。因此,当您进行断言时,浏览器中显示的页面已更改或正在更改。