BeautifulSoup的基本用法
Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式。
它是一个灵活又方便的网页解析库,处理高效,支持多种解析器。
利用它就不用编写正则表达式也能方便的实现网页信息的抓取。
通常人们把 beautifulSoup 叫作“美味的汤,绿色的浓汤”,简称:美丽(味)汤
它的官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html (中)
https://www.crummy.com/software/BeautifulSoup/bs4/doc/ (英)
安装
快速安装
pip install beautifulsoup4 或 easy_install BeautifulSoup4
解析库
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐安装。
# -*- coding:utf-8 -*- from bs4 import BeautifulSoup html = """haha,The Dormouse's story The Dormouse's story
Once upon a time there were three little sisters; and their names were , Lacie and Tillie; and they lived at the bottom of a well.
...
""" soup = BeautifulSoup(html, 'lxml') print(soup) # 输出解析的html对象 print(soup.prettify()) # 格式化 print(soup.title) # 输出标题,eg: print(soup.title.string) # 输出title标题的内容字符串 print(soup.title.parent.name) # 输出haha,The Dormouse's story 节点父节点的名字 print(soup.find_all('a')) # 输出所有标签组成的list print(soup.find(id='link3')) # 返回包含id='link3'的标签所有内容