面向新手解析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入门篇之字典
Oct 17 Python
python使用xlrd模块读写Excel文件的方法
May 06 Python
Python内建模块struct实例详解
Feb 02 Python
python的格式化输出(format,%)实例详解
Jun 01 Python
浅谈python str.format与制表符\t关于中文对齐的细节问题
Jan 14 Python
对python列表里的字典元素去重方法详解
Jan 21 Python
快速排序的四种python实现(推荐)
Apr 03 Python
pytorch获取vgg16-feature层输出的例子
Aug 20 Python
Python Print实现在输出中插入变量的例子
Dec 25 Python
解决tensorflow由于未初始化变量而导致的错误问题
Jan 06 Python
python属于哪种语言
Aug 16 Python
python多次执行绘制条形图
Apr 20 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脚本[带参数]的方法
2010/01/22 PHP
利用PHP自动生成印有用户信息的名片
2016/08/01 PHP
网页上的Javascript编辑器和代码格式化
2010/04/25 Javascript
jQuery实现长文字部分显示代码
2013/05/13 Javascript
js怎么判断flash swf文件是否加载完毕
2014/08/14 Javascript
javascript使用window.open提示“已经计划系统关机”的原因
2014/08/15 Javascript
jquery轮播的实现方式 附完整实例
2016/07/28 Javascript
javascript回到顶部特效
2016/07/30 Javascript
js实现简单的碰壁反弹效果
2016/08/30 Javascript
jQueryUI 拖放排序遇到滚动条时有可能无法执行排序的小bug及解决方案
2016/12/19 Javascript
微信小程序购物车、父子组件传值及calc的注意事项总结
2018/11/14 Javascript
element-ui 中使用upload多文件上传只请求一次接口
2019/07/19 Javascript
使用 webpack 插件自动生成 vue 路由文件的方法
2019/08/20 Javascript
vue实现购物车选择功能
2020/01/10 Javascript
[01:20]PWL S2开团时刻第三期——团战可以输 蝙蝠必须死
2020/11/26 DOTA
python通过shutil实现快速文件复制的方法
2015/03/14 Python
python获取一组汉字拼音首字母的方法
2015/07/01 Python
Python简单计算文件MD5值的方法示例
2018/04/11 Python
python使用tornado实现简单爬虫
2018/07/28 Python
如何利用Boost.Python实现Python C/C++混合编程详解
2018/11/08 Python
用python脚本24小时刷浏览器的访问量方法
2018/12/07 Python
对Python3 * 和 ** 运算符详解
2019/02/16 Python
Python爬虫抓取技术的一些经验
2019/07/12 Python
解决pytorch 数据类型报错的问题
2021/03/03 Python
css3动画效果抖动解决方法
2018/09/03 HTML / CSS
html5如何及时更新缓存文件(js、css或图片)
2013/06/24 HTML / CSS
html5 input输入实时检测以及延时优化
2018/07/18 HTML / CSS
美国最大的农村生活方式零售店:Tractor Supply Company(TSC)
2017/05/15 全球购物
美国时尚大码女装购物网站:Avenue
2019/05/24 全球购物
Tommy Hilfiger澳洲官网:美国高端休闲领导品牌
2020/12/16 全球购物
企业车辆管理制度
2014/01/24 职场文书
学习雷锋活动总结
2014/04/29 职场文书
2014国庆节幼儿园亲子活动方案
2014/09/16 职场文书
养成教育主题班会
2015/08/13 职场文书
解决pytorch 损失函数中输入输出不匹配的问题
2021/06/05 Python
一篇文章了解正则表达式的替换技巧
2022/02/24 Javascript