溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

xpath的使用:定位,獲取文本和屬性值

發(fā)布時(shí)間:2020-06-16 09:41:17 來源:網(wǎng)絡(luò) 閱讀:5932 作者:提著筆記本 欄目:編程語言

myPage = '''<html>
<title>TITLE</title>
<body>
<h2></h2>
<div>
</div>
<div id="photos">
<img src="pic1.jpeg"/><span id="pic1">*</span>
<img src="pic2.jpeg"/><span id="pic2">****
</span>
<p><a href="http://www.example.com/more_pic.html">*
</a></p>
<a href="http://www.baidu.com">****</a>
<a href="http://www.163.com">*****</a>
<a href="http://www.sohu.com">****</a>
</div>
<p class="myclassname">Hello,\nworld!<br/>-- by Adam</p>
<div class="foot">放在尾部的其他一些說明</div>
</body>
</html>'''

html = etree.fromstring(myPage)


#一、定位
divs1 = html.xpath('//div')
divs2 = html.xpath('//div[@id]')
divs3 = html.xpath('//div[@class="foot"]')
divs4 = html.xpath('//div[@]')
divs5 = html.xpath('//div[1]')
divs6 = html.xpath('//div[last()-1]')
divs7 = html.xpath('//div[position()<3]')
divs8 = html.xpath('//div|//h2')
divs9 = html.xpath('//div[not(@
)]')


二、取文本 text() 區(qū)別 html.xpath('string()')

text1 = html.xpath('//div/text()')
text2 = html.xpath('//div[@id]/text()')
text3 = html.xpath('//div[@class="foot"]/text()')
text4 = html.xpath('//div[@*]/text()')
text5 = html.xpath('//div[1]/text()')
text6 = html.xpath('//div[last()-1]/text()')
text7 = html.xpath('//div[position()<3]/text()')
text8 = html.xpath('//div/text()|//h2/text()')


#三、取屬性 @
value1 = html.xpath('//a/@href')
value2 = html.xpath('//img/@src')
value3 = html.xpath('//div[2]/span/@id')


#四、定位(進(jìn)階)
#1.文檔(DOM)元素(Element)的find,findall方法
divs = html.xpath('//div[position()<3]')
for div in divs:
ass = div.findall('a') # 這里只能找到:div->a, 找不到:div->p->a
for a in ass:
if a is not None:
#print(dir(a))
print(a.text, a.attrib.get('href')) #文檔(DOM)元素(Element)的屬性:text, attrib

2.與1等價(jià)

a_href = html.xpath('//div[position()<3]/a/@href')
print(a_href)

#3.注意與1、2的區(qū)別
a_href = html.xpath('//div[position()<3]//a/@href')
print(a_href)

參考:https://www.cnblogs.com/hhh6460/p/5079465.html

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI