我正在使用Selenium WebDriver和Python。我有一个如下代码。当我使用assert <some variable> in driver.page_source
时,为什么会出现AssertionError?如果我使用文字(例如字符串),则测试通过而不是变量。
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import sys
from instream import InStream
from outstream import OutStream
import stdio
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_search_in_python_org(self):
driver = self.driver
s = 'Ireland'
driver.get("http://www.python.org")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert s in driver.page_source
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
答案 0 :(得分:2)
这是计时问题(也可以将其复制)。断言是在尚未加载搜索结果的时刻进行的,因此Ireland
中还没有page_source
。通过WebDriverWait
添加等待以使测试更可靠:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Firefox()
s = 'Ireland'
driver.get("http://www.python.org")
wait = WebDriverWait(driver, 10)
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
# wait for results to be visible
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".list-recent-events li")))
assert s in driver.page_source
请注意,.list-recent-events li
是一个 CSS选择器,它与结果事件列表中的第一个事件相匹配。