使用变量而不是文字时的AssertionError

时间:2016-06-12 19:50:54

标签: python selenium webdriver

我正在使用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()

1 个答案:

答案 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选择器,它与结果事件列表中的第一个事件相匹配。