爬虫-BeautifulSoup
一个灵活又方便的网页解析库,处理高效,支持多种解析器。
利用它就不用编写正则表达式也能方便的实现网页信息的抓取
概念
HTML或XML的解析器,依赖于lxml
支持解析库
- lxml
速度快,文档容错能力强(不规范会自动补全);用的比较多 - html.parser
python自带的解析库;速度一般,文档容错能力一般 - xml
速度快,文档容错能力强
优缺点
- 优点:简单
- 缺点:性能差
解析速度对比
正则 > xpath > beautifulsoup4
安装
1 | python -m pip install beautifulsoup4 |
或
1 | conda install beautifulsoup4 |
导入模块
1 | from bs4 import BeautifulSoup |
使用
创建对象
1 | # html是需要解析的文档 |
查找节点
1 | rObj = soup.find('div',attrs={"id":"aaa"}) |
常用方法
- soup.find()
- soup.find_all()
1
2r_list=soup.find_all(属性名="属性值")
r_list=soup.find_all(class_="test")如果属性名是class;由于class是Python的关键字,所以我们要写class_
1
2
3r_list=soup.find_all("节点名", attrs={"名":"值"})
r_list=soup.find_all("div", attrs={"class":"test"}) - 节点对象.string、
只能获取当前节点的文本内容(不包括子节点) - 节点对象.get_text()
获取所有节点文本内容(包括子节点)