1. 程式人生 > >web中的CSS、Xpath等路徑定位方法學習

web中的CSS、Xpath等路徑定位方法學習

理論 公司 mov border pre -s usr 屬性 chrom

今天不到八點就到公司了,來的比較早,趁著有點時間,總結下web中的CSS、Xpath等路徑定位定位的方式吧!

簡單的介紹下xpath和css的定位

理論知識就不羅列了

還是利用博客園的首頁、直接附上代碼:

這個是xpath

 1 #!/usr/bin/env python
 2 # -*- coding: utf_8 -*-
 3 
 4 from learn_webdriver import Webdriver
 5 from selenium import webdriver
 6 from selenium.webdriver.common.action_chains import ActionChains
 7 from time import sleep
 8 
 9 browser_chrome = webdriver.Chrome(Webdriver.chrome())
10 browser_chrome.get("http://www.cnblogs.com/")
11 
12 sleep(2)
13 ActionChains(browser_chrome).move_to_element(browser_chrome.find_element_by_xpath(".//li[@id=‘cate_item_2‘]")).perform()
14 # 鼠標懸停在左側“編程語言”導航欄上
15 browser_chrome.find_element_by_xpath(".//a[@href=‘/cate/python/‘]").click()
16 sleep(2)
17 browser_chrome.quit()

XPath 是一門在 XML 文檔中查找信息的語言

使用的是函數是 find_element_by_xpath

這裏總結了xpath的表達式:

表達式

說明

案例

節點名稱

選取節點下所有子節點

body

body 下所有子節點

/

從根節點選取

body/div

body 下所有 div 節點

//

匹配選擇節點

不考慮位置

//div

不考慮位置的 div 節點

.

當前節點

..

當前節點的父節點

@

選取屬性

.//li[@id=‘cate_item_2‘]

li節點 且屬性id=cate_item_2

下面是css

 1 #!/usr/bin/env python
 2 # -*- coding: utf_8 -*-
 3 
 4 from learn_webdriver import Webdriver
 5 from selenium import webdriver
 6 from selenium.webdriver.common.action_chains import ActionChains
 7 from time import sleep
 8 
 9 browser_chrome = webdriver.Chrome(Webdriver.chrome())
10 browser_chrome.get("http://www.cnblogs.com/")
11 
12 sleep(2)
13 ActionChains(browser_chrome).move_to_element(browser_chrome.find_element_by_css_selector("li[id = ‘cate_item_2‘]")).perform()
14 # 鼠標懸停在左側“編程語言”導航欄上
15 browser_chrome.find_element_by_css_selector("a[href = ‘/cate/python/").click()
16 sleep(2)
17 browser_chrome.quit()

css更加靈活一些

css使用的函數是 find_element_by_css_selector

web中的CSS、Xpath等路徑定位方法學習