爬虫-BeautifulSoup

一个灵活又方便的网页解析库,处理高效,支持多种解析器。
利用它就不用编写正则表达式也能方便的实现网页信息的抓取

概念

HTML或XML的解析器,依赖于lxml

支持解析库

  1. lxml
    速度快,文档容错能力强(不规范会自动补全);用的比较多
  2. html.parser
    python自带的解析库;速度一般,文档容错能力一般
  3. xml
    速度快,文档容错能力强

优缺点

  1. 优点:简单
  2. 缺点:性能差

解析速度对比
正则 > xpath > beautifulsoup4

安装

1
python -m pip install beautifulsoup4

1
conda install beautifulsoup4

导入模块

1
from bs4 import BeautifulSoup

使用

创建对象

1
2
3
# html是需要解析的文档
# lxml是指定的解析库
soup = BeautifulSoup(html, 'lxml')

查找节点

1
2
rObj = soup.find('div',attrs={"id":"aaa"})
rList = soup.find_all('div',attrs={})

常用方法

  1. soup.find()
  2. soup.find_all()
    1
    2
        r_list=soup.find_all(属性名="属性值")
    r_list=soup.find_all(class_="test")

    如果属性名是class;由于class是Python的关键字,所以我们要写class_

    1
    2
    3
    r_list=soup.find_all("节点名", attrs={"名":"值"})

    r_list=soup.find_all("div", attrs={"class":"test"})
  3. 节点对象.string、
    只能获取当前节点的文本内容(不包括子节点)
  4. 节点对象.get_text()
    获取所有节点文本内容(包括子节点)