u=1022646614,1081030420&fm=26&gp=0.jpg
xpath常用方法
# 從任意位置選擇節(jié)點(diǎn)
xpath('//')
# a下的文本
xpath('//a/text()')
# a下所有的文本
xpath('//a//text()')
# 當(dāng)前路徑
xpath('.')
# @符號(hào)`
xpath('a/@href')
xpath('div[@class='a']')
# `text()`
xpath('a[text()='下一頁']')
#上一級(jí)
xpath('..')
xpath('//a[1]')
xpath('//a[last()]')
xpath('//a[postion()<4]')
xpath('//a[1]|//a[5]')
xpath('a[contains(text(),"下一頁")]')
常用定位元素的方法
# 通過id定位元素的方法是一樣的。' //* '代表所有標(biāo)簽
xpath('//*[@id='kw']')
# 通過name定位元素的方法是一樣的。
xpath('//*[@name='wd']')
# //input 代表匹配所有input標(biāo)簽灸撰,
# 后邊再加上[@class='s_ipt']代表class屬性是s_ipt的input標(biāo)簽磕蛇。
xpath('//input[@class='s_ipt']')
# / 是絕對(duì)定位,從最上面的一個(gè)標(biāo)簽開始,
# 存在相同的標(biāo)簽可以加上[1]、[2]、[3]等攒读。
xpath('/html/body/form/span/input')
# 先定位class='soutu-btn'的span標(biāo)簽,然后再找其下的input標(biāo)簽辛友。
xpath('//span[@class='soutu-btn']/input')
# 先定位id='form'的form標(biāo)簽薄扁,然后再找其下的/span/input標(biāo)簽剪返。
xpath('//form[@id='form']/span/input')
# 找出id='kw'并且name='wd'的input標(biāo)簽。
# 這種可以方便找出那些沒有id和name的標(biāo)簽邓梅,
# 畢竟如果有id或者name的
# 話就用id定位元素或者name定位元素了脱盲。
xpath('//input[@id='kw' and @name='wd']')
# 選取屬于 bookstore 子元素的第一個(gè) book 元素。
xpath('/bookstore/book[1]')
# 選取屬于 bookstore 子元素的最后一個(gè) book 元素日缨。
xpath('/bookstore/book[last()]')
# 選取屬于 bookstore 子元素的倒數(shù)第二個(gè) book 元素钱反。
xpath('/bookstore/book[last()-1]')
# 選取最前面的兩個(gè)屬于 bookstore 元素的子元素的 book 元素。
xpath('/bookstore/book[position()<3]')
# 選取所有擁有名為 lang 的屬性的 title 元素匣距。
xpath('//title[@lang]')
# 選取所有 title 元素面哥,且這些元素?fù)碛兄禐?eng 的 lang 屬性。
xpath('//title[@lang=’eng’]')
# 選取 bookstore 元素的所有 book 元素毅待,
# 且其中的 price 元素的值須大于 35.00
xpath('/bookstore/book[price>35.00]')
# 選取 bookstore 元素中的 book 元素的所有 title 元素
# 且其中的 price 元素的值須大于 35.00尚卫。
xpath('/bookstore/book[price>35.00]/title')
一些常用函數(shù)
# 1、 starts-with函數(shù) 獲取以xxx開頭的元素
xpath('//div[stars-with(@class,”test”)]')
# 2尸红、contains函數(shù) 獲取包含xxx的元素
xpath('//div[contains(@id,”test”)]')
# 3吱涉、and 與的關(guān)系
xpath('//div[contains(@id,”test”) and contains(@id,”title”)]')
# 4、 text()函數(shù)
xpath('//div[contains(text(),”test”)]')
xpath('//div[@id=”“test]/text()')