標籤:key orm 滑鼠 move usr browser idt bin 節點
今天不到八點就到公司了,來的比較早,趁著有點時間,總結下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等路徑定位方法學習