四、xpath –在 lxml中使用xpath語法
?
在 lxml?中使用 XPath?語法:
?
1、獲取所有li標簽:
2、獲取所有li元素下的所有class屬性的值:
3、獲取li標簽下href為www.baidu.com的a標簽:
4、獲取li標簽下所有span標簽:
5、獲取li標簽下的a標簽里的所有class:
6、獲取最后一個li的a的href屬性對應的值:
7、獲取倒數第二個li元素的內容:
8、獲取倒數第二個li元素的內容的第二種方式:
Html 文件代碼:
<!DOCTYPE html>
<html lang ="en">
<head>
? ? <title>Title</title>
</head>
<body>
<div>
? ? <ul>
? ? ? ? <li class = "item-0"><a href = "link1.html">frist item</a></li>
? ? ? ? <li class = "item-1"><a href = "link2.html">second item</a></li>
? ? ? ? <li class = "item-inactive"><a href = "link3.html"><span class = "bold">third item</span></a></li>
? ? ? ? <li class = "item-1"><a href = "link4.html">fourth item</a></li>
? ? ? ? <li class = "item-0"><a href = "link5.html">fifth item</a></li>
? ? </ul>
</div>
</body>
</html>
語法練習代碼:
from lxml import etree
html = etree.parse('hello.html')
?
# 1、獲取所有li標簽:
result = html.xpath('//li')
print(result)
fori in result:
??? print(etree.tostring(i))
# 2、獲取所有li元素下的所有class屬性的值:
result = html.xpath('//li/@class')
print(result)
# 3、獲取li標簽下href為www.baidu.com的a標簽:
result = html.xpath('//li/a[@href = "www.baidu.com"]')
print(result)
# 4、獲取li標簽下所有span標簽:
?
result = html.xpath('//li//span')
print(result)
fori in result:
???? print(etree.tostring(i))
# 5、獲取li標簽下的a標簽里的所有class:
result = html.xpath('//li/a//@class')
print(result)
# 6、獲取最后一個li的a的href屬性對應的值:
?
result = html.xpath('//li[last()]/a/@href')
print(result)
# 7、獲取倒數第二個li元素的內容:
result = html.xpath('//li[last()-1]/a')
print(result)
print(result[0].text)? ??# 獲取內容
# 8、獲取倒數第二個li元素的內容的第二種方式:
result = html.xpath('//li[last()-1]/a/text()')
print(result)
上一篇文章 第三章 數據解析(三) 2019-12-13 地址:?
http://www.lxweimin.com/p/a5195487e51f
下一篇文章 第三章 數據解析(五) 2019-12-15 地址:
http://www.lxweimin.com/p/dda1a316a8ae
以上資料內容來源網絡,僅供學習交流,侵刪請私信我,謝謝。