一步一步学爬虫(3)网页解析之Beautiful Soup的使用

3.2 网页解析之Beautiful Soup的使用

3.2.1 Beautiful Soup的简介

  • 一种简单的处理导航、搜索、修改、解析功能的工具库。部分替代正则表达式,能自动将输入的文档转换为Unicode编码,将输出文档转换为utf-8编码,大大提高了解析网页的效率。

3.2.2 解析器

  • Beautiful Soup支持的解析器
解析器 使用方法 优势 劣势
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格式的文档 速度慢不依赖外部扩展
  • 推荐使用lxml作为解析器,因为效率更高. 在Python2.7.3之前的版本和Python3中3.2.2之前的版本,必须安装lxml或html5lib, 因为那些Python版本的标准库中内置的HTML解析方法不够稳定。举例如下:

    from bs4 import BeautifulSoup
    soup = BeautifulSoup('<p>Hello</p>', "lxml")
    print(soup.p)
    print(soup.p.string)
    print(soup.p.text)
    print(type(soup.p.string))
    print(type(soup.p.text))
    

    运行结果如下:

    <p>Hello</p>
    Hello
    Hello
    <class 'bs4.element.NavigableString'>
    <class 'str'>	
    

3.2.3 准备工作

  安装解析器

pip3 install lxml
pip3 install beautifulsoup4

3.2.4 基本使用

  • 举例
html_doc = """
<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>
"""

from bs4 import BeautifulSoup

# lxml为解析器
soup = BeautifulSoup(html_doc, "lxml")
# 格式化输出代码
print(soup.prettify())
print(soup.title.string)
  • 首先,调用prettify方法,这个方法解析出来的字符串以标准缩进格式输出。
  • 然后,调用soup.title.string,输出HTML中title节点的文本内容。

3.2.5 节点选择器

  • 还是以上面HTML代码为例。加上几个节点,如下:
print(soup.title)			# 获取title
print(soup.title.string)	# 获取title内容
print(soup.head)			# 获取head
print(soup.p)				# 获取p内容
  • 运行结果:
<title>The Dormouse's story</title>
The Dormouse's story
<head><title>The Dormouse's story</title></head>
<p class="title"><b>The Dormouse's story</b></p>

3.2.6 提取信息

  • 继续上面代码的提取。
print(soup.title.name)          # 获取标题名字
print(soup.p.attrs)             # 获取属性和属性值
print(soup.p.attrs['name'])     # 获取name属性值
print(soup.p['name'])           # 获取name属性值
print(soup.p['class'])          # 获取class属性值,如果多个class则注意
print(soup.p.string)            # 获取内容
  • 运行结果
title
{
   'class': ['title'], 'name': 'dromouse'}
dromouse
dromouse
['title']
The Dormouse's story
  • 嵌套选择
# 嵌套选择
print(soup.head.title)          # head头内容
print(type(soup.head.title))    # head头内容类型
print(soup.head.title.string)   # head头内容文本
  • 运行结果
<title>The Dormouse's story</title>
<class 'bs4.element.Tag'>
The Dormouse's story
  • bs4的返回结果都是bs4.element.Tag类型可以根据节点嵌套选择。

3.2.7 关联选择

  • 先选中某一节点,再以它为基准选子节点、父(祖先)节点、兄弟节点等。

contents方法

html = """
<html>
	<head>
		<title>The Dormouse's story</title>
	</head>
    <body>        
        <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>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朝兮暮兮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值