python 爬虫入门到进阶(四)

tsvico Lv5

https://gss1.bdstatic.com/-vo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268/sign=e2a135117d1ed21b79c929e3956fddae/faedab64034f78f092033e1079310a55b2191ccc.jpg

HTML 代码解析,从获取到的源码中获取数据

 

如果想从网页中提取想要的数据,可能会有人想到正则匹配,但是正则匹配虽然强大,但是对于不熟悉的人来说比较容易出错,这里我们就要提到一个更加强大的工具 Beautiful Soup

Beautiful Soup 简介

Beautiful Soup 是 python 的一个库,主要是从网页抓取数据,支持编码自动转换

Beautiful Soup 安装

可以利用 pip 或者 easy_install 来安装,以下两种方法均可

1
easy_install beautifulsoup4
1
pip p install beautifulsoup4

如果想手动安装,可以访问下边地址

Beautiful Soup

解压后执行

1
sudo python setup.py install

Beautiful Soup 支持 Python 标准库中的 HTML 解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python 默认的解析器,lxml 解析器更加强大,速度更快,推荐安装。

安装 lxml

1
pip install lxml
解析器使用方法优势劣势
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 语言库
html5libBeautifulSoup(markup, “html5lib”)最好的容错性以浏览器的方式解析文档生成 HTML5 格式的文档速度慢不依赖外部扩展

最好的教程 官方文档

如何使用

将一段文档传入 BeautifulSoup 的构造方法,就能得到一个文档的对象,可以传入一段字符串或一个文件句柄.

1
2
3
4
5
from bs4 import BeautifulSoup

soup = BeautifulSoup(open("index.html"))

soup = BeautifulSoup("<html>data</html>")

首先,文档被转换成 Unicode, 并且 HTML 的实例都被转换成 Unicode 编码

1
2
BeautifulSoup("Sacr&eacute; bleu!")
<html><head></head><body>Sacré bleu!</body></html>

然后,Beautiful Soup 选择最合适的解析器来解析这段文档,如果手动指定解析器那么 Beautiful Soup 会选择指定的解析器来解析文档.(参考 解析成 XML ).

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# encoding: utf-8
#Beautiful Soup解析HTML数据
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</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"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" 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>
"""
soup = BeautifulSoup(html,'lxml')
#从本地HTML文件创建对象
#soup = BeautifulSoup(open('index.html'))
#格式化输出soup
print soup.prettify() #格式化输出代码
print soup.title #输出标题
print soup.head #输出head
#
print soup.name

注释掉格式化代码后的结果

image

实战篇:

下一节:妹子图爬取

  • 标题: python 爬虫入门到进阶(四)
  • 作者: tsvico
  • 创建于 : 2018-06-19 00:34:05
  • 更新于 : 2021-03-06 20:21:07
  • 链接: https://blog.tbox.fun/2018/ee7cf874.html
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
python 爬虫入门到进阶(四)