Xpath简介:
1.xpath,全称为XML Path language,是一种在XML文档中查找信息的语言,同样适用于HTML文档中信息的查找
2.基本用法用法
import requests
from lxml import etree
text = '''
<div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</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>
</ul>
</div>
'''
html=etree.HTML(text) # 将上述字符串解析为HTML文档,构造Xpath的解析对象
result=etree.tostring(html) # 这里是将html文档进行完成的修正
print(result.decode('utf-8')) # 输出结果会自动补全htnl完成格式
<html><body><div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</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>
2.1 还可以直接读取html文档,构建Xpath解析对象
from lxml import etree
html=etree.parse('./text.html',etree.HTMLParser()) #读取html文档并构建xpath解析对象
result=etree.tostring(html)
print(result.decode('utf-8')) #输出结果跟上面基本吻合,会有一些乱码现象,但是都会补上缺失的li标签
3.
路径表达式 | 描述 |
---|---|
/bookstore/book[1] | 选取bookstore下的第一个子元素 |
/bookstore/book[last()] | 选取bookstore下的倒数第二个book元素。 |
bookstore/book[position()❤️] | 选取bookstore下前面两个子元素。 |
//book[@price] | 选取拥有price属性的book元素 |
//book[@price=10] | 选取所有属性price等于10的book元素 |
4.利用xpath来具体实战一下
import requests
from lxml import etree
from html.parser import HTMLParser
def qiyuan_splder():
header={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'}
seed_url='http://eas.huat.edu.cn/'
result=requests.get(seed_url,headers=header)
html=etree.HTML(result.text)
response=html.xpath('//div[@class="nostyle"]/ul/li/a/text()')
print(response)
with open('wocaonima.txt','w',encoding='utf-8') as aa:
for i in response:
text=str(i)
aa.write(text+'\n')
if __name__ == '__main__':
qiyuan_splder()
1.上诉代码,首先需要导入requests请求网址相关的库和lxml
2.requests中的get方法获得网址的请求文本,这是就需要用到etree中的HTML类将文本进行初始化,转为HTML格式,以便使用xpath进行解析提取相关信息
3.根据xpath相关节点的路径表达式进行信息的提取,但是会发现提取的结果是一个列表形式的element对象,如果想要提取相关的信息,则只需要在相关路径后面再加上 /text()即可
4,文件写入,对上述提取的信息列表进行for 循环遍历
text本上就是字符串类型,text+‘\n’ 就可以完成换行写入文件