面向新手解析python Beautiful Soup基本用法


Posted in Python onJuly 11, 2020

Beautiful Soup就是Python的一个HTML或XML的解析库,可以用它来方便地从网页中提取数据。它有如下三个特点:

  • Beautiful Soup提供一些简单的、Python式的函数来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。
  • Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为UTF-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时你仅仅需要说明一下原始编码方式就可以了。
  • Beautiful Soup已成为和lxml、html6lib一样出色的Python解释器,为用户灵活地提供不同的解析策略或强劲的速度。

首先,我们要安装它:pip install bs4,然后安装 pip install beautifulsoup4.

Beautiful Soup支持的解析器

面向新手解析python Beautiful Soup基本用法

下面我们以lxml解析器为例:

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

结果:

Hello

beautiful soup美化的效果实例:

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" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" 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, 'lxml')#调用prettify()方法。这个方法可以把要解析的字符串以标准的缩进格式输出
print(soup.prettify())
print(soup.title.string)

结果:

<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 class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">
  <!-- Elsie -->
  </a>
  ,
  <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">
  Lacie
  </a>
  and
  <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">
  Tillie
  </a>
  ;
and they lived at the bottom of a well.
 </p>
 <p class="story">
  ...
 </p>
 </body>
</html>
The Dormouse's story

下面举例说明选择元素、属性、名称的方法

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" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" 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, 'lxml')
print('输出结果为title节点加里面的文字内容:\n',soup.title)
print('输出它的类型:\n',type(soup.title))
print('输出节点的文本内容:\n',soup.title.string)
print('结果是节点加其内部的所有内容:\n',soup.head)
print('结果是第一个p节点的内容:\n',soup.p)
print('利用name属性获取节点的名称:\n',soup.title.name)
#这里需要注意的是,有的返回结果是字符串,有的返回结果是字符串组成的列表。
# 比如,name属性的值是唯一的,返回的结果就是单个字符串。
# 而对于class,一个节点元素可能有多个class,所以返回的是列表。
print('每个节点可能有多个属性,比如id和class等:\n',soup.p.attrs)
print('选择这个节点元素后,可以调用attrs获取所有属性:\n',soup.p.attrs['name'])
print('获取p标签的name属性值:\n',soup.p['name'])
print('获取p标签的class属性值:\n',soup.p['class'])
print('获取第一个p节点的文本:\n',soup.p.string)

结果:

输出结果为title节点加里面的文字内容:
<title>The Dormouse's story</title>
输出它的类型:
<class 'bs4.element.Tag'>
输出节点的文本内容:
The Dormouse's story
结果是节点加其内部的所有内容:
<head><title>The Dormouse's story</title></head>
结果是第一个p节点的内容:
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
利用name属性获取节点的名称:
title
每个节点可能有多个属性,比如id和class等:
{'class': ['title'], 'name': 'dromouse'}
选择这个节点元素后,可以调用attrs获取所有属性:
dromouse
获取p标签的name属性值:
dromouse
获取p标签的class属性值:
['title']
获取第一个p节点的文本:
The Dormouse's story

在上面的例子中,我们知道每一个返回结果都是bs4.element.Tag类型,它同样可以继续调用节点进行下一步的选择。

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print('获取了head节点元素,继续调用head来选取其内部的head节点元素:\n',soup.head.title)
print('继续调用输出类型:\n',type(soup.head.title))
print('继续调用输出内容:\n',soup.head.title.string)

结果:

获取了head节点元素,继续调用head来选取其内部的head节点元素:
 <title>The Dormouse's story</title>
继续调用输出类型:
 <class 'bs4.element.Tag'>
继续调用输出内容:
 The Dormouse's story

(1)find_all()

find_all,顾名思义,就是查询所有符合条件的元素。给它传入一些属性或文本,就可以得到符合条件的元素,它的功能十分强大。

find_all(name , attrs , recursive , text , **kwargs)

他的用法:

html='''
<div class="panel">
  <div class="panel-heading">
    <h4>Hello</h4>
  </div>
  <div class="panel-body">
    <ul class="list" id="list-1">
      <li class="element">Foo</li>
      <li class="element">Bar</li>
      <li class="element">Jay</li>
    </ul>
    <ul class="list list-small" id="list-2">
      <li class="element">Foo</li>
      <li class="element">Bar</li>
    </ul>
  </div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print('查询所有ul节点,返回结果是列表类型,长度为2:\n',soup.find_all(name='ul'))
print('每个元素依然都是bs4.element.Tag类型:\n',type(soup.find_all(name='ul')[0]))
#将以上步骤换一种方式,遍历出来
for ul in soup.find_all(name='ul'):
  print('输出每个u1:',ul.find_all(name='li'))
#遍历两层
for ul in soup.find_all(name='ul'):
  print('输出每个u1:',ul.find_all(name='li'))
  for li in ul.find_all(name='li'):
    print('输出每个元素:',li.string)

结果:

查询所有ul节点,返回结果是列表类型,长度为2:
 [<ul class="list" id="list-1">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>, <ul class="list list-small" id="list-2">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>]
每个元素依然都是bs4.element.Tag类型:
 <class 'bs4.element.Tag'>
输出每个u1: [<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>]
输出每个u1: [<li class="element">Foo</li>, <li class="element">Bar</li>]
输出每个u1: [<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>]
输出每个元素: Foo
输出每个元素: Bar
输出每个元素: Jay
输出每个u1: [<li class="element">Foo</li>, <li class="element">Bar</li>]
输出每个元素: Foo
输出每个元素: Bar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python中split方法用法分析
Apr 17 Python
在Python中使用全局日志时需要注意的问题
May 06 Python
Windows上使用virtualenv搭建Python+Flask开发环境
Jun 07 Python
python 2.6.6升级到python 2.7.x版本的方法
Oct 09 Python
利用Python脚本生成sitemap.xml的实现方法
Jan 31 Python
Python入门之三角函数全解【收藏】
Nov 08 Python
Python面向对象程序设计类的封装与继承用法示例
Apr 12 Python
Django分页功能的实现代码详解
Jul 29 Python
PyQt+socket实现远程操作服务器的方法示例
Aug 22 Python
使用Python进行防病毒免杀解析
Dec 13 Python
pytorch载入预训练模型后,实现训练指定层
Jan 06 Python
Python随机数函数代码实例解析
Feb 09 Python
基于python实现判断字符串是否数字算法
Jul 10 #Python
基于python实现计算两组数据P值
Jul 10 #Python
Python3爬虫中关于Ajax分析方法的总结
Jul 10 #Python
Python3爬虫中Ajax的用法
Jul 10 #Python
Python3爬虫中Selenium的用法详解
Jul 10 #Python
Python3爬虫中Splash的知识总结
Jul 10 #Python
Python3爬虫里关于Splash负载均衡配置详解
Jul 10 #Python
You might like
基于php-fpm 参数的深入理解
2013/06/03 PHP
jquery+php+ajax显示上传进度的多图片上传并生成缩略图代码
2014/10/15 PHP
PHP pear安装配置教程
2016/05/14 PHP
PHP  实现等比压缩图片尺寸和大小实例代码
2016/10/08 PHP
thinkPHP实现的联动菜单功能详解
2017/05/05 PHP
PHP 7.0新增加的特性介绍
2017/06/08 PHP
laravel excel 上传文件保存到本地服务器功能
2019/11/14 PHP
一个JavaScript继承的实现
2006/10/24 Javascript
javascript 正则表达式相关应介绍
2012/11/27 Javascript
js如何判断用户是否是用微信浏览器
2014/06/05 Javascript
JavaScript中实现异步编程模式的4种方法
2014/09/24 Javascript
Javascript中获取对象的原型对象的方法小结
2015/02/25 Javascript
jquery渐隐渐显的图片幻灯闪烁切换实现方法
2015/02/26 Javascript
javascript日期格式化方法小结
2015/12/17 Javascript
自己动手制作基于jQuery的Web页面加载进度条插件
2016/06/03 Javascript
javascript超过容器后显示省略号效果的方法(兼容一行或者多行)
2016/07/14 Javascript
浅谈Vue网络请求之interceptors实际应用
2018/02/28 Javascript
JavaScript常见继承模式实例小结
2019/01/11 Javascript
利用JavaScript的Map提升性能的方法详解
2019/08/14 Javascript
基于JavaScript实现随机点名器
2021/02/25 Javascript
决策树的python实现方法
2014/11/18 Python
Python实现Const详解
2015/01/27 Python
用Python脚本来删除指定容量以上的文件的教程
2015/05/04 Python
用python写的一个wordpress的采集程序
2016/02/27 Python
Python简单计算文件MD5值的方法示例
2018/04/11 Python
Python中多个数组行合并及列合并的方法总结
2018/04/12 Python
python切片及sys.argv[]用法详解
2018/05/25 Python
Python实现基于POS算法的区块链
2018/08/07 Python
python实现复制大量文件功能
2019/08/31 Python
Pytorch训练过程出现nan的解决方式
2020/01/02 Python
python报错: 'list' object has no attribute 'shape'的解决
2020/07/15 Python
CSS3转换功能transform主要属性值分析及实现分享
2012/05/06 HTML / CSS
比较基础的php面试题及答案-编程题
2012/10/14 面试题
写一个在SQL Server创建表的SQL语句
2012/03/10 面试题
优秀的毕业生的自我评价
2013/12/12 职场文书
网站文案策划岗位职责
2015/04/14 职场文书