Lxml库和Xpath语法及其使用
lxml库
lxml库是我用起来最舒服的一个库了。
lxml库安装:pip install lxml。
进入环境from lxml import etree,如果没有报错,那就安装好了。
lxml相比BeautifulSoup最大的优点就是速度快
etree可以把HTML文档解析为Element对象
具体操作如下:
import requests
from lxml import etree
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
}
res = requests.get('https://www.bilibili.com/',headers = headers)
html = etree.parse(res.text)
print(type(html))
lxml库还有着许多妙用,比如说,自动修正HTML代码。
如果读取的HTML文件缺了闭合标签&#