我正在用 Selenium 编写文本,它获取表格最左边的列并验证其单元格中的字符串是否与我拥有的日期列表相匹配。我的代码看起来像这样:
dates = ["20130501", "20130502", "20130506", "20130507", "20130508", "20130509", "20130510", "20130513", "20130514", "20130515"]
mytable = self.driver.find_element(By.ID, "mytable")
datecells = mytable.find_elements(By.CSS_SELECTOR, "tbody td:first-child")
for date, cell in zip(dates, datecells):
print "'{0}', '{1}'".format(date, cell.text) # For debugging
#self.assertEqual(date, cell.text)
当断言被注释掉时,我得到了这样的打印结果:
'20130501', '' "20130502', '' '20130506', '' '20130507', '' '20130508', '' '20130509', '' '20130510', '' '20130513', '' '20130514', '' '20130515', ''
奇怪的是,如果我在打印上放置一个断点(将 MyEclipse 与 PyDev 结合使用),并在输出之前查看 PyDev Debug 的变量选项卡中的单元格,我可以看到正确的文本,并且代码输出为预期:
'20130501', '20130501' '20130502', '20130502' '20130506', '20130506' '20130507', '20130507' '20130508', '20130508' '20130509', '20130509' '20130510', '20130510' '20130513', '20130513' '20130514', '20130514' '20130515', '20130515'
WebElement .text 属性是否存在一些奇怪的观察者效应怪癖,它只能由该调试器正确评估,或者是否存在我应该等待的某些条件以便从单元格中获取正确的值而无需步骤通过?
最佳答案
在对 PhantomJS 的 WebDriver 进行了一些测试后,我能够确定这是 Firefox 的 WebDriver 的一个问题,并发现了这个先前提出的问题:WebElement getText() is an empty string in Firefox if element is not physically visible on the screen
所以把for循环改成
for date, cell in zip(dates, datecells):
self.driver.execute_script("arguments[0].scrollIntoView(true);", cell)
print "'{0}', '{1}'".format(date, cell.text)
self.assertEqual(date, cell.text)
为了在获取文本之前将每个单元格滚动到 View 中,我得到了预期的输出。
关于python - Python Selenium WebElements 和 .text 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17156632/