面向新手解析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实现二分法算法实例
Feb 02 Python
python以环状形式组合排列图片并输出的方法
Mar 17 Python
利用Python画ROC曲线和AUC值计算
Sep 19 Python
python实现图片处理和特征提取详解
Nov 13 Python
Python简单实现的代理服务器端口映射功能示例
Apr 08 Python
pygame游戏之旅 计算游戏中躲过的障碍数量
Nov 20 Python
python使用Plotly绘图工具绘制水平条形图
Mar 25 Python
python ChainMap 合并字典的实现步骤
Jun 11 Python
Python使用百度api做人脸对比的方法
Aug 28 Python
pycharm修改file type方式
Nov 19 Python
Python中lru_cache的使用和实现详解
Jan 25 Python
Python极值整数的边界探讨分析
Sep 15 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编程最快明白》第四讲:日期、表单接收、session、cookie
2010/11/01 PHP
PHP详解ASCII码对照表与字符转换
2011/12/05 PHP
php缓冲 output_buffering和ob_start使用介绍
2014/01/30 PHP
PHP下 Mongodb 连接远程数据库的实例代码
2017/08/30 PHP
PHP+redis实现的限制抢购防止商品超发功能详解
2019/09/19 PHP
PHP 范围解析操作符(::)用法分析【访问静态成员和类常量】
2020/04/14 PHP
JS代码优化技巧之通俗版(减少js体积)
2011/12/23 Javascript
关于JQuery($.load)事件的用法和分析
2013/04/09 Javascript
基于JavaScript 声明全局变量的三种方式详解
2013/05/07 Javascript
jQuery使用each方法与for语句遍历数组示例
2016/06/16 Javascript
React Native之TextInput组件解析示例
2017/08/22 Javascript
基于JS实现html中placeholder属性提示文字效果示例
2018/04/19 Javascript
layui的面包屑或者表单不显示的解决方法
2019/09/05 Javascript
JS的时间格式化和时间戳转换函数示例详解
2020/07/27 Javascript
在Uni中使用Vue的EventBus总线机制操作
2020/07/31 Javascript
跟老齐学Python之做一个小游戏
2014/09/28 Python
Python实现更改图片尺寸大小的方法(基于Pillow包)
2016/09/19 Python
python和flask中返回JSON数据的方法
2018/03/26 Python
Python中list查询及所需时间计算操作示例
2018/06/21 Python
python 实现A*算法的示例代码
2018/08/13 Python
Python基于plotly模块实现的画图操作示例
2019/01/23 Python
python爬虫模拟浏览器访问-User-Agent过程解析
2019/12/28 Python
将pytorch转成longtensor的简单方法
2020/02/18 Python
python实现学生信息管理系统(精简版)
2020/11/27 Python
python爬取豆瓣电影排行榜(requests)的示例代码
2021/02/18 Python
慕尼黑山地运动、户外服装和体育用品专家:Sporthaus Schuster
2019/08/27 全球购物
Huda Beauty官方商店:化妆和美容产品
2020/09/05 全球购物
初三政治教学反思
2014/01/30 职场文书
简历里的自我评价
2014/01/31 职场文书
城管综合整治方案
2014/05/01 职场文书
酒店七夕情人节活动策划方案
2014/08/24 职场文书
幼儿教师暑期培训方案
2014/08/27 职场文书
入党转正介绍人意见
2015/06/03 职场文书
二胎满月酒致辞
2015/07/29 职场文书
党员电教片《信仰》心得体会
2016/01/15 职场文书
MySQL 1130异常,无法远程登录解决方案详解
2021/08/23 MySQL