>[info]WebUI自動化,**首先需要定位元素**,然后再進行各種事件操作。
WebDriver 提供了一系列的API,提供給我們方便得定位元素。
WebDriver類的源碼位置:`selenium\webdirver\remote\webdirver.py`
通過源碼分析,WebDriver中有一系列以`find_`開頭的方法,都是用于元素定位。下面我們一一介紹這些定位的方法。
[TOC]
這里,初學者可以根據下面的實例來一一了解如何進行元素的定位。
## 環境準備
首先創建一個hello.html頁面,用于下面的演示
```html
<!DOCTYPE html>
<html lang="zh-CN">
<body>
<h1 class="head_title">你好,<span id="world">世界!</span></h1>
<a href="http://www.hmoore.net/@guanfuchang" target="_blank">我的看云首頁</a>
<br/>
<br/>
<div id="login_form" class="login">
用戶名:<input name="username" class="ptqa user_name" placeholder="用戶名" value="Milton" required/>
密碼:<input type="text" name="password" class="ptqa pwd" placeholder="密碼" value="ptqa" required/>
地區:
<select class="city">
<option value="gz">廣州</option>
<option value="fs">佛山</option>
<option value="mm">茂名</option>
<option value="hb">襄樊</option>
</select>
<br>
<br>
<button>提交</button>
<br>
</div>
</body>
</html>
```
在同個目錄下創建一個`find_location.py`文件,初始化工作
```python
from selenium import webdriver
import os
# 創建Chrome驅動實例
driver = webdriver.Chrome()
# 啟動瀏覽器并且導航到指定URL
# 這里為了覆蓋更多的元素定位,我自己編寫了一個本地的hello.html文件。
file_path = 'file:///' + os.path.abspath('hello.html')
driver.get(file_path)
```
## 元素定位
### 通過class定位
`find_element_by_class_name(self, name):`
`find_elements_by_class_name(self, name):`
```python
# 定位class名稱為“head_title"的元素
head_title = driver.find_element_by_class_name("head_title")
print(head_title.text)
```
### 通過id定位
`find_element_by_id(self, id_):`
`find_elements_by_id(self, id_):`
```python
# 定位id為“world”的元素
world = driver.find_element_by_id("world")
print(world.text)
```
### 通過name屬性定位
`find_element_by_name(self, name):`
`find_elements_by_name(self, name):`
```python
# 定位name為“username”的元素
username = driver.find_element_by_name("username")
print(username.get_attribute("value"))
```
### 通過標簽名定位
`find_element_by_tag_name(self, name):`
`find_elements_by_tag_name(self, name):`
```python
# 定位標簽為<button>的元素
submit_btn = driver.find_element_by_tag_name("button")
print(submit_btn.text)
```
### 通過鏈接文本定位
`find_element_by_link_text(self, link_text):`
`find_element_by_partial_link_text(self, link_text):`
```python
# 定位鏈接文本完全匹配“我的看云首頁”的元素
kancloud = driver.find_element_by_link_text("我的看云首頁")
print(kancloud.get_attribute("href"))
```
```python
# 定位鏈接文本部分匹配“看云首頁”的元素
kancloud = driver.find_element_by_partial_link_text("看云首頁")
print(kancloud.get_attribute("href"))
```
### 通過xpath定位
`find_element_by_xpath(self, xpath):`
`find_elements_by_xpath(self, xpath):`
```python
# xpath定位,相對路徑定位用戶名輸入框
username = driver.find_element_by_xpath("//body/div/input")
print(username.get_attribute("value"))
```
```python
# xpath定位,相對路徑與屬性結合 定位密碼輸入框
password = driver.find_element_by_xpath("//input[@name='password']")
print(password.get_attribute("value"))
```
```python
# xpath定位,多個屬性結合 定位密碼輸入框
password = driver.find_element_by_xpath("//input[@name='password'][@type='text']")
print(password.get_attribute("value"))
```
### 通過css選擇器定位
`find_element_by_css_selector(self, css_selector):`
`find_elements_by_css_selector(self, css_selector):`

```python
# css選擇器,標簽+屬性 定位用戶名輸入框
username = driver.find_element_by_css_selector("input[name='username']")
print(username.get_attribute("value"))
```
```python
# css選擇器,標簽+class類名 定位用戶名輸入框
username = driver.find_element_by_css_selector("input.user_name")
print(username.get_attribute("value"))
```
```python
# css選擇器,標簽+多個class類名,定位密碼輸入框,注意不要空格,空格代表下一級子元素
password = driver.find_element_by_css_selector("input.ptqa.pwd")
print(password.get_attribute("value"))
```
```python
# css選擇器,id+多個class類名,定位密碼輸入框
password = driver.find_element_by_css_selector("#login_form .ptqa.pwd")
print(password.get_attribute("value"))
```
```python
# css選擇器,多級class類名,定位密碼輸入框
password = driver.find_element_by_css_selector(".login .ptqa.pwd")
print(password.get_attribute("value"))
```
```python
# css選擇器,class類名+屬性,定位密碼輸入框
password = driver.find_element_by_css_selector(".login .ptqa[name='password']")
print(password.get_attribute("value"))
```
```python
#css 選擇器,根據父子關系,定位密碼輸入框
password = driver.find_element_by_css_selector("div[id='login_form']>input[name='password']")
print(password.get_attribute("value"))
```
```python
# css 選擇器,根據兄弟關系,定位密碼輸入框
password = driver.find_element_by_css_selector("input[name='username']+input")
print(password.get_attribute("value"))
```
上面的定位元素方法,都列出了兩個,其中一個是 **find_elements_by_xxx**,這個方法用在獲取結果有多個元素的情況,例如下面獲取下拉列表選項
```python
# 用find_element_by_css_selector 獲取的是單個元素
mm = driver.find_element_by_class_name("city").find_element_by_css_selector("option[value='mm']")
print(mm.text)
print("-"*20)
# 用find_elements_by_css_selector獲取的是元素組列表
cities = driver.find_elements_by_css_selector(".city option")
print(type(cities))
for city in cities:
print(city.text)
```
運行結果為:
```cmd
茂名
--------------------
<class 'list'>
廣州
佛山
茂名
襄樊
```
### 通用的終極定位語法
上面的所有元素定位 `find_element_by_xxx`和`find_elements_by_xxx`調用的結果,實際上都是在調用以下兩種方法,我們也可以直接調用一下兩種方法即可。
`find_element(self, by=By.ID, value=None):`
`find_elements(self, by=By.ID, value=None):`
```python
class By(object):
"""
Set of supported locator strategies.
"""
ID = "id"
XPATH = "xpath"
LINK_TEXT = "link text"
PARTIAL_LINK_TEXT = "partial link text"
NAME = "name"
TAG_NAME = "tag name"
CLASS_NAME = "class name"
CSS_SELECTOR = "css selector"
```
例如:
```python
from selenium.webdriver.common.by import By
# 根據id,定位id為“world”的元素
world = driver.find_element(By.ID,"world")
print(world.text)
```
```python
# xpath定位,相對路徑與屬性結合 定位密碼輸入框
password = driver.find_element(By.XPATH,"//input[@name='password']")
print(password.get_attribute("value"))
```
```python
# css選擇器,標簽+屬性 定位用戶名輸入框
username = driver.find_element(By.CSS_SELECTOR,"input[name='username']")
print(username.get_attribute("value"))
```
## 定位總結
通過本節,我們需要數量掌握以下幾種元素定位方法
* 通過id定位
* 通過class定位
* 通過name屬性定位
* 通過標簽名定位
* 通過鏈接文本定位
* 通過xpath定位
* 通過css選擇器定位
我最喜歡的定位方式,優先是id,如果沒有id找class,如果class不好定位,找css選擇器。我覺得css選擇器是最靈活也是最強大的定位方式。使用xpath定位切記不要用絕對路徑,最好結合相對路徑與屬性。
<hr style="margin-top:50px">
<section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="margin: 40px 0% 10px;box-sizing: border-box;"><section class="" style="display: inline-block;width: 100%;border-width: 5px;border-style: double;border-color: rgb(23, 22, 24);padding: 10px;border-radius: 2px;box-sizing: border-box;"><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="transform: translate3d(20px, 0px, 0px);-webkit-transform: translate3d(20px, 0px, 0px);-moz-transform: translate3d(20px, 0px, 0px);-o-transform: translate3d(20px, 0px, 0px);font-size: 11px;margin: -50px 0% 0px;box-sizing: border-box;"><section class="" style="box-sizing: border-box;width: 7em;height: 7em;display: inline-block;vertical-align: bottom;border-radius: 100%;border-width: 4px;border-style: double;border-color: rgb(23, 22, 24);background-position: center center;background-repeat: no-repeat;background-size: cover;background-image: url("http://pav7h2emv.bkt.clouddn.com/FnD-fHkNDLN1-b02XmnMvsz6ld-n");"><section class="" style="width: 100%;height: 100%;overflow: hidden;box-sizing: border-box;"><img class="" data-ratio="0.6012024" data-w="499" data-src="http://pav7h2emv.bkt.clouddn.com/FnD-fHkNDLN1-b02XmnMvsz6ld-n" style="opacity: 0; box-sizing: border-box; width: 100% !important; height: auto !important; visibility: visible !important;" width="100%" data-type="jpeg" _width="100%" src="http://pav7h2emv.bkt.clouddn.com/FnD-fHkNDLN1-b02XmnMvsz6ld-n" data-fail="0"></section></section></section></section><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="margin: -30px 0% 30px;box-sizing: border-box;"><section class="" style="display: inline-block;vertical-align: top;width: 61.8%;padding: 0px 15px;box-sizing: border-box;"><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="margin: 40px 0% 0px;box-sizing: border-box;"><section class="" style="color: rgb(160, 160, 160);box-sizing: border-box;"><p style="margin: 0px;padding: 0px;box-sizing: border-box;">微信公眾號:</p><p style="margin: 0px;padding: 0px;box-sizing: border-box;">python測試開發圈</p><p style="margin: 0px;padding: 0px;box-sizing: border-box;"><br style="box-sizing: border-box;"></p></section></section></section></section><section class="" style="display: inline-block;vertical-align: top;width: 38.2%;box-sizing: border-box;"><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="text-align: center;margin: 10px 0% 0px;box-sizing: border-box;"><section class="" style="max-width: 100%;vertical-align: middle;display: inline-block;border-width: 0px;border-radius: 0px;box-shadow: rgb(0, 0, 0) 0px 0px 0px;width: 90%;overflow: hidden !important;box-sizing: border-box;"><img data-ratio="1" data-w="430" data-src="http://pav7h2emv.bkt.clouddn.com/FibGgIJSMfHtehzeWOOzjdQKSMx5" style="vertical-align: middle; max-width: 100%; box-sizing: border-box; width: 100% !important; height: auto !important; visibility: visible !important;" width="100%" data-type="jpeg" _width="100%" class="" src="http://pav7h2emv.bkt.clouddn.com/FibGgIJSMfHtehzeWOOzjdQKSMx5" data-fail="0"></section></section></section></section></section></section><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="margin: -30px 0% 0px;box-sizing: border-box;"><section class="" style="display: inline-block;vertical-align: top;width: 61.8%;padding: 0px 15px;box-sizing: border-box;"><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="transform: translate3d(5px, 0px, 0px);-webkit-transform: translate3d(5px, 0px, 0px);-moz-transform: translate3d(5px, 0px, 0px);-o-transform: translate3d(5px, 0px, 0px);box-sizing: border-box;"><section class="" style="color: rgb(160, 160, 160);font-size: 14px;box-sizing: border-box;"><p style="margin: 0px;padding: 0px;box-sizing: border-box;">一起分享學習與成長路線</p></section></section></section></section><section class="" style="display: inline-block;vertical-align: top;width: 38.2%;box-sizing: border-box;"><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="transform: translate3d(10px, 0px, 0px);-webkit-transform: translate3d(10px, 0px, 0px);-moz-transform: translate3d(10px, 0px, 0px);-o-transform: translate3d(10px, 0px, 0px);box-sizing: border-box;"><section class="" style="color: rgb(160, 160, 160);font-size: 14px;box-sizing: border-box;"><p style="margin: 0px;padding: 0px;box-sizing: border-box;">長按(或掃描)二維碼關注</p></section></section></section></section></section></section></section></section></section>