The driver.get method will navigate to a page given by the URL. WebDriver will wait until the page has
fully loaded (that is, the “onload” event has fired) before returning control to your test or script. It’s
worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has
completely loaded.
WebDriver offers a number of ways to find elements using one of the find_element_by_* methods.
For example, the input text element can be located by its name attribute using find_element_by_na
me method
WebDriver 提供了许多寻找网页元素的方法,譬如 find_element_by_* 的方法。例如一个输入框可
以通过 find_element_by_name 方法寻找 name 属性来确定。
Next we are sending keys, this is similar to entering keys using your keyboard. Special keys can be s
end using Keys class imported from selenium.webdriver.common.keys
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def test_search_in_python_org(self):
driver = self.driver
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 "No results found." not in driver.page_source
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
运行程序,同样的功能,我们将其封装为测试标准类的形式。
The test case class is inherited from unittest.TestCase. Inheriting from TestCase class is the way to te
ll unittest module that this is a test case. The setUp is part of initialization, this method will get called b
efore every test function which you are going to write in this test case class. The test case method s
hould always start with characters test. The tearDown method will get called after every test method.
This is a place to do all cleanup actions. You can also call quit method instead of close. The quit will e
xit the entire browser, whereas close will close a tab, but if it is the only tab opened, by default most
browser will exit entirely.
测试用例是继承了 unittest.TestCase 类,继承这个类表明这是一个测试类。setUp方法是初始化的方
法,这个方法会在每个测试类中自动调用。每一个测试方法命名都有规范,必须以 test 开头,会自
动执行。最后的 tearDown 方法会在每一个测试方法结束之后调用。这相当于最后的析构方法。在这
个方法里写的是 close 方法,你还可以写 quit 方法。不过 close 方法相当于关闭了这个 TAB 选项卡,
然而 quit 是退出了整个浏览器。当你只开启了一个 TAB 选项卡的时候,关闭的时候也会将整个浏览
器关闭。
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_elements_by_tag_name("input")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
你还可以通过它的文本链接来获取,但是要小心,文本必须完全匹配才可以,所以这并不是一个很
好的匹配方式。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC