Webdriver在IE8中无法找到元素

0 投票
3 回答
1356 浏览
提问于 2025-04-16 23:44

在这个简化的测试中,不管我用什么方式去找元素,webdriver都找不到我想要的那个元素。

import unittest
from selenium import webdriver

class Setups(unittest.TestCase):
    def setUp(self):
        self.browser = webdriver.Ie()
        self.browser.implicitly_wait(15)

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

class IETest(Setups):
    def test_ietest(self):
        br = self.browser
        br.get("http://www.gmail.com")
        br.find_element_by_id("Email").send_keys("anything")

if __name__ == '__main__':
    unittest.main(verbosity=2)

当隐式等待超时,试图找到一个id为"Email"的元素时,输出中会出现以下错误信息:

test_ietest (__main__.IETest) ... ERROR

======================================================================
ERROR: test_ietest (__main__.IETest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "V:\Automation\Tests\web_ietest.py", line 23, in test_ietest
    br.find_element_by_id("Email").send_keys("anything")
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 172, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 525, in find_element
    {'using': by, 'value': value})['value']
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 144, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py"
, line 118, in check_response
    raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: u'Unable to find element with id == Email'

----------------------------------------------------------------------
Ran 1 test in 19.707s

FAILED (errors=1)

用find_by_xpath和find_by_css_selector来运行同样的测试,结果也是一样。当然,使用Firefox运行同样的测试是没有问题的。

我在谷歌上找不到答案,有没有人知道为什么IE就是找不到那些明显存在的页面元素呢?

一些技术信息:

  • 操作系统:Windows 7 64位
  • Selenium版本:2.4.0
  • Python版本:2.7.1
  • 浏览器:Internet Explorer 8.0.7601.17514 64位

经过一些额外的调查发现,在尝试使用find_element之前,页面源代码已经完全加载并且是正确的。在get(url)find_element_by_id之间加上以下代码,可以打印出页面源代码,并且id为"Email"的元素确实存在:

print unicode(br.page_source).encode("utf-8")

尝试直接print br.page_source时出现了一些编码错误,这就是为什么打印的代码里包含了unicode编码的内容。我不确定在使用IE时这是否正常,或者utf-8编码是否影响了我找到元素的尝试。


所以,我想真正的问题是:有没有人成功在64位的Internet Explorer上使用Webdriver的Python API?

3 个回答

0

这是一个Java的例子,但你可以从中学到一些东西。

我发现一个很好的排查问题的方法是先使用一个没有异常的调用,比如这样:

Set<WebElement> found = driver.findElements( By.cssSelector("some selector") );

然后,再像这样使用findElement:

if ( found.size() == 0 ) {
    Assert.assertTrue("Found zero x", found.size() == 1 );
} else if ( found.size() == 1 ) {
    WebElement x = found.iterable().next();
} else {
    Assert.assertTrue("Error looking for x", found.size() >= 1 );
}

这样做的话,当找不到元素时,它就不会抛出异常。相反,你会得到一个人类可读的错误信息。

0

你有没有试着把隐式等待的超时时间调长一点?

2

我在IE8上一直没法解决这个问题。

不过,安装了IE9之后,所有的元素都能正常找到,跟我预期的一样。

撰写回答