使用下面的简化测试,无论我使用哪种类型的find_by调用,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:AutomationTestsweb_ietest.py", line 23, in test_ietest
br.find_element_by_id("Email").send_keys("anything")
File "C:Python27libsite-packagesseleniumwebdriverremotewebdriver.py", l
ine 172, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "C:Python27libsite-packagesseleniumwebdriverremotewebdriver.py", l
ine 525, in find_element
{'using': by, 'value': value})['value']
File "C:Python27libsite-packagesseleniumwebdriverremotewebdriver.py", l
ine 144, in execute
self.error_handler.check_response(response)
File "C:Python27libsite-packagesseleniumwebdriverremoteerrorhandler.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中也可以正常运行。
Google让我失望了,有没有人知道为什么IE拒绝找到明显存在的页面元素?
技术信息:- Windows 7 64位
- 硒测试盒框 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")
尝试仅打印br。page_source抛出一些编码错误,这就是为什么打印行包含unicode编码的东西。不确定在使用IE时是否符合预期,或者utf-8编码是否会阻碍我查找元素的尝试。
所以,我想真正的问题是:有没有人成功地使用了64位Internet Explorer的Webdriver Python API ?
我一直无法在IE8上解决这个问题。
但是在安装IE9之后,元素可以像预期的那样被找到。
是否尝试增加隐式等待超时?
这是一个Java的例子,但是你可以从中学习。
我发现一个好的故障排除技术是首先使用像这样的无异常调用:
Set<WebElement> found = driver.findElements( By.cssSelector("some selector") );
然后,像这样执行finelement:
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 );
}
这样,当没有找到时,它不会抛出异常。相反,您会得到一个可读的错误。