# 1. 概括
- 获取页面: urllib, requests
- 解析页面信息: 正则表达式, BeautifulSoup4(BS4)
# 2. BS4简介
Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个
工具箱,通过解析文档为tiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。
你不需要考虑编码方式,除非文档没有指定一个编一下原始编码方式就可以了。
# 3. BS4的4种对象
## 2-1. BeautifulSoup对象
## 2-2. Tag对象
Tag就是html中的一个标签,用BeautifulSoup就能解析出来Tag的具体内容,
具体的格式为soup.name,其中name是html下的标签。
bs4中可以运用的四个解析器
解析器:使用方法:优势:劣势
Python标准库
BeautifulSoup(markup, "html.parser")
Python的内置标准库
执行速度适中
文档容错能力强
Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差
lxml
HTML 解析器 BeautifulSoup(markup, "lxml")
速度快
文档容错能力强
需要安装C语言库
lxml
XML 解析器
BeautifulSoup(markup, ["lxml-xml"])
BeautifulSoup(markup, "xml")
速度快
唯一支持XML的解析器
需要安装C语言库
html5lib
BeautifulSoup(markup, "html5lib")
最好的容错性
以浏览器的方式解析文档
生成HTML5格式的文档
速度慢
不依赖外部扩展
bs4的基本使用方式
import re
from bs4 import BeautifulSoup
html="""
<html>
<head><title>story12345</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><span>westos</span><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister1" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
<input type='password'>...</input>
"""
#生成一个bs4对象,同时html.parser为html的解析方式
soup=BeautifulSoup(html,'html.parser')
#优化html,使其模式更完整(会补充相应的不完整的标签)
soup.prettify()
# 1. 根据标签获取内容;
# ******************标签的常用属性************************
# # 根据格式化, 如果title只有一个, 根据标签可以获取
print(soup.title)
# 标签的名称
print(soup.title.name)
# 获取标签里面的属性信息
print(soup.a.attrs)
# # *******************标签常用的方法*************************
# #get方法用于得到标签下的属性值,注意这是一个重要的方法,在许多场合都能用到,