由於python製做自動化腳本網頁須要定位到相關元素html
方法參考:https://selenium-python.readthedocs.io/getting-started.htmlnode
特開一門隨筆給使用xpath定位python
它是什麼spa
語法:code
Expression | Description |
---|---|
nodename | Selects all nodes with the name "nodename" |
/ | Selects from the root node |
// | Selects nodes in the document from the current node that match the selection no matter where they are |
. | Selects the current node |
.. | Selects the parent of the current node |
@ | Selects attributes |
表達 | 描述 |
節點名稱 | 選擇名稱爲「節點名稱」的全部節點 |
/ | 從根節點中選擇 |
// | 從當前節點中選擇與選擇匹配的文檔中的節點,不管它們在何處 |
. | 選擇當前節點 |
.. | 選擇當前節點的父節點 |
@ | 選擇屬性 |
下表中列出了一些路徑表達式和表達式的結果:xml
示例:htm
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <bookstore> 4 5 <book> 6 <title lang="en">Harry Potter</title> 7 <price>29.99</price> 8 </book> 9 10 <book> 11 <title lang="en">Learning XML</title> 12 <price>39.95</price> 13 </book> 14 15 </bookstore>
Path Expression | Result |
---|---|
bookstore | Selects all nodes with the name "bookstore" |
/bookstore | Selects the root element bookstore Note: If the path starts with a slash ( / ) it always represents an absolute path to an element!blog |
bookstore/book | Selects all book elements that are children of bookstore |
//book | Selects all book elements no matter where they are in the document |
bookstore//book | Selects all book elements that are descendant of the bookstore element, no matter where they are under the bookstore element |
//@lang | Selects all attributes that are named lang |
路徑表達 | 結果 |
bookstore | 選擇名稱爲「bookstore」的全部節點 |
/bookstore | 選擇根元素「bookstore」ip 注意:若是路徑以斜槓(/)開頭,它老是表示元素的絕對路徑!element |
bookstore/book | 選擇做爲書店子項的全部書元素 |
//book | 選擇全部書籍元素,不管它們在文檔中的位置 |
bookstore//book | 選擇bookstore元素後代的全部book元素,不管它們在bookstore元素下的哪一個位置 |
//@lang | 選擇名爲lang的全部屬性 |
用於查找特定節點或包含特定值的節點。
謂詞老是嵌在方括號中。
在下表中,咱們列出了一些帶謂詞的路徑表達式和表達式的結果:
依舊是以上示例
/bookstore/book[1] | 選擇第一個book元素做爲bookstore元素的子元素。 注意:在IE 5,6,7,8,9中,第一個節點是[0],但根據W3C,它是[1]。要在IE中解決此問題,請將SelectionLanguage設置爲XPath: 在JavaScript中:xml.setProperty(「SelectionLanguage」,「XPath」); |
/bookstore/book[last()] | 選擇做爲bookstore元素的子元素的最後一個book元素 |
/bookstore/book[last()-1] | 選擇最後一個book元素,它是bookstore元素的子元素 |
/bookstore/book[position()<3] | 選擇做爲bookstore元素的子元素的前兩個book元素 |
//title[@lang] | 選擇具備名爲lang的屬性的全部標題元素 |
//title[@lang='en'] | 選擇具備值爲「en」的「lang」屬性的全部標題元素 |
/bookstore/book[price>35.00] | 選擇bookstore元素的全部book元素,其price元素的值大於35.00 |
/bookstore/book[price>35.00]/title | 選擇bookstore元素的book元素的全部title元素,其中price元素的值大於35.00 |
XPath通配符可用於選擇未知的XML節點。
通配符 | 說明 |
* | 匹配任何元素節點 |
@* | 匹配任何屬性節點 |
node() | 匹配任何類型的任何節點 |
在下表中,咱們列出了一些路徑表達式和表達式的結果:
路徑 | 說明 |
/bookstore/* | 選擇bookstore元素的全部子元素節點 |
//* | 選擇文檔中的全部元素 |
//title[@*] | 選擇具備至少一個任何類型屬性的全部標題元素 |
路徑 | 表達效果 |
//book/title | //book/price | 選擇全部書元素的全部標題和價格元素 |
//title | //price | 選擇文檔中的全部標題和價格元素 |
/bookstore/book/title | //price | 選擇bookstore元素的book元素的全部title元素和文檔中的全部price元素 |