一、什么是Selenium
Selenium是一个用于web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。
参考文档:Selenium with Python中文翻译文档 — Selenium-Python中文文档 2 documentation
驱动下载:http://chromedriver.storage.googleapis.com/index.html
二、常用元素定位方法
-
根据id定位
<html>
<body>
<form id="loginForm">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Login" />
</form>
</body>
<html>
我们可以这样定位表单元素form
login_form = driver.find_element_by_id('loginForm')
-
根据Name定位
<html>
<body>
<form id="loginForm">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Login" />
<input name="continue" type="button" value="Clear" />
</form>
</body>
<html>
username和password元素,可以这样定位:
username = driver.find_element_by_name('username')
password = driver.find_element_by_name('password')
下面这个操作会返回Login按钮,因为它在Clear按钮的前面:
continue = driver.find_element_by_name('continue')
-
根据XPath定位
<html>
<body>
<form id="loginForm">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Login" />
<input name="continue" type="button" value="Clear" />
</form>
</body>
<html>
form元素可以这样定位:
login_form = driver.find_element_by_xpath("/html/body/form[1]")login_form = driver.find_element_by_xpath("//form[1]")login_form = driver.find_element_by_xpath("//form[@id='loginForm']")
-
用链接文本定位超链接
<html>
<body>
<p>Are you sure you want to do this?</p>
<a href="continue.html">Continue</a>
<a href="cancel.html">Cancel</a>
</body>
<html>
可以这样定位continue.html链接:
continue_link = driver.find_element_by_link_text('Continue')
continue_link = driver.find_element_by_partial_link_text('Conti')
-
标签名定位
知道元素标签名就使用这个定位,如果没有元素匹配,会抛出NoSuchElementException异常。
<html>
<body>
<h1>Welcome</h1>
<p>Site content goes here.</p>
</body>
<html>
可以这样定位标题元素(h1):
heading1 = driver.find_element_by_tag_name('h1')
-
class定位
知道class就使用这个定位,只返回匹配的第一个,无元素匹配,会抛出NoSuchElementException
异常。
<html>
<body>
<p class="content">Site content goes here.</p>
</body>
<html>
定位p元素:
content = driver.find_element_by_class_name('content')
-
css选择器定位
如果你能用css选择器的语法来表述一个元素,那么就选这个,只返回匹配的第一个,无元素匹配,会抛出NoSuchElementException
异常。
<html>
<body>
<p class="content">Site content goes here.</p>
</body>
<html>
定位p元素:
content = driver.find_element_by_css_selector('.content')