1.创建 Beautiful Soup 对象

  1. from bs4 import BeautifulSoup
  2.  
  3. html = """
  4. <html><head><title>The Dormouse's story</title></head>
  5. <body>
  6. <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
  7. <p class="story">Once upon a time there were three little sisters; and their names were
  8. <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
  9. <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
  10. <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
  11. and they lived at the bottom of a well.</p>
  12. <p class="story">...</p>
  13. """
  14.  
  15. soup = BeautifulSoup(html)
  16. print soup.prettify()

2.四大对象种类

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:

  • Tag
  • NavigableString
  • BeautifulSoup
  • Comment

2.1 tag

  1. print soup.title
  2. #<title>The Dormouse's story</title>
  3.  
  4. print soup.head
  5. #<head><title>The Dormouse's story</title></head>
  6.  
  7. print soup.a
  8. #<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
  9.  
  10. print soup.p
  11. #<p class="title" name="dromouse"><b>The Dormouse's story</b></p>

2.2 name

  1. print soup.name
  2. #[document]
  3.  
  4. print soup.head.name
  5. #head

2.3 attrs

  1. print soup.p.attrs
  2. #{'class': ['title'], 'name': 'dromouse'}
  1. print soup.p['class']
  2. #['title']
  3.  
  4. print soup.p.get('class')
  5. #['title']
  6.  
  7. //可以进行修改和删除
  8. soup.p['class']="newClass"
  9. print soup.p
  10. #<p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>
  11.  
  12. del soup.p['class']
  13. print soup.p
  14. #<p name="dromouse"><b>The Dormouse's story</b></p>

(2)NavigableString

  1. print soup.p.string
  2. #The Dormouse's story

3.搜索文档树

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

find_all() 方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件

1)name 参数

name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉

A.传字符串

最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的<b>标签

  1. print soup.find_all('a')
  2. #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

B.传正则表达式

如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以b开头的标签,这表示<body>和<b>标签都应该被找到

  1. import re
  2. for tag in soup.find_all(re.compile("^b")):
  3. print(tag.name)
  4. # body
  5. # b

C.传列表

如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有<a>标签和<b>标签

  1. soup.find_all(["a", "b"])
  2. # [<b>The Dormouse's story</b>,
  3. # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
  4. # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
  5. # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

D.传 True

True 可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点

  1. for tag in soup.find_all(True):
  2. print(tag.name)
  3. # html
  4. # head
  5. # title
  6. # body
  7. # p
  8. # b
  9. # p
  10. # a
  11. # a

E.传方法

如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 [4] ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False

下面方法校验了当前元素,如果包含 class 属性却不包含 id 属性,那么将返回 True:

  1. def has_class_but_no_id(tag):
  2. return tag.has_attr('class') and not tag.has_attr('id')
  3.  
  4. print soup.find_all(has_class_but_no_id)
  5. # [<p class="title"><b>The Dormouse's story</b></p>,
  6. # <p class="story">Once upon a time there were...</p>,
  7. # <p class="story">...</p>]

2)keyword 参数

  1. soup.find_all(id='link2')
  2. # [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
  3.  
  4. soup.find_all(href=re.compile("elsie"))
  5. # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
  6.  
  7. soup.find_all(href=re.compile("elsie"), id='link1')
  8. # [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
  9.  
  10. soup.find_all("a", class_="sister")
  11. # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
  12. # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
  13. # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性 ,但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag

  1. data_soup.find_all(attrs={"data-foo": "value"})
  2. # [<div data-foo="value">foo!</div>]

python 爬虫5 Beautiful Soup的用法的更多相关文章

  1. python爬虫之Beautiful Soup基础知识+实例

    python爬虫之Beautiful Soup基础知识 Beautiful Soup是一个可以从HTML或XML文件中提取数据的python库.它能通过你喜欢的转换器实现惯用的文档导航,查找,修改文档 ...

  2. Python爬虫之Beautiful Soup解析库的使用(五)

    Python爬虫之Beautiful Soup解析库的使用 Beautiful Soup-介绍 Python第三方库,用于从HTML或XML中提取数据官方:http://www.crummv.com/ ...

  3. python 爬虫利器 Beautiful Soup

    python 爬虫利器 Beautiful Soup Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文 ...

  4. [Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息

    [Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息 2018-07-21 23:53:02 larger5 阅读数 4123更多 分类专栏: 网络爬虫   版权声明: ...

  5. python爬虫之Beautiful Soup的基本使用

    1.简介 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据.官方解释如下: Beautiful Soup提供一些简单的.python式的函数用来处理导航.搜索 ...

  6. Python爬虫库-Beautiful Soup的使用

    Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库,简单来说,它能将HTML的标签文件解析成树形结构,然后方便地获取到指定标签的对应属性. 如在上一篇文章通过爬虫 ...

  7. Python爬虫之Beautiful Soup库的基本使用

  8. Python爬虫利器二之Beautiful Soup的用法

    上一节我们介绍了正则表达式,它的内容其实还是蛮多的,如果一个正则匹配稍有差池,那可能程序就处在永久的循环之中,而且有的小伙伴们也对写正则表达式的写法用得不熟练,没关系,我们还有一个更强大的工具,叫Be ...

  9. Python之Beautiful Soup的用法

    1. Beautiful Soup的简介 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据.官方解释如下: Beautiful Soup提供一些简单的.pyt ...

随机推荐

  1. 【SQL Server】sql server更改了数据表的字段/新增数据表的字段 无法保存

    sql server更改了数据表的字段/新增数据表的字段  无法保存 解决方法:进入 工具-->选项-->Designers-->表设计器和数据库设计器-->取消勾选   即可

  2. Oracle API Gateway连接WebService服务,攻击保护

    1.启动和连接OAG OAG连接的时候除了不选择analysis,其他都选上,然后启动Gateway实例以及Nodemanager. 命令如下: /$OAG_HOME/apigateway/posix ...

  3. 腾讯云linux服务器分区方案

    刚刚在腾讯云买了一台服务器,刚买的服务器的数据盘都是需要自己来分区的,下面就记录一下操作. 通过命令fdisk-l查看硬盘信息 可以看到有两块硬盘/dev/vda和/dev/vdb,启动vda是系统盘 ...

  4. 深度增强学习--Policy Gradient

    前面都是value based的方法,现在看一种直接预测动作的方法 Policy Based Policy Gradient 一个介绍 karpathy的博客 一个推导 下面的例子实现的REINFOR ...

  5. mac更新系统后Git不能用,提示missing xcrun at

    今天更新了mac系统,然后就踩了这个坑. 启动AndroidStudio 右上角提示: can't start git: /usr/bin/git probably the path to git e ...

  6. 解决MySQL数据导入报错Got a packet bigger than‘max_allowed_packet’bytes

    临时修改:mysql>set global max_allowed_packet=524288000;修改 #512M 这条语句可以在小黑窗里执行,也可以在navicat查询新建查询里执行.

  7. perl学习笔记——目录操作

    在目录书中移动 chdir 操作副改变当前的工作目录.它和shell中cd命令类似: chdir ‘/etc’ or die “cannot chdir to /etc:$1”; 注意:工作目录不能更 ...

  8. 倍福TwinCAT(贝福Beckhoff)应用教程13.2 TwinCAT控制松下伺服 CS说明

    虚拟仿真上,要注意仿真只是为了可视化,可以看到数据的变动是否和实际一致,所以Robot2D才是主要因素,虚拟仿真采集机器人的关节位置或者TCP位置来显示而已,为了测试一些别的算法,我们还可以在虚拟仿真 ...

  9. Linux——配置使用github

    前一段时间在windows下配置了github的环境,参考“TortoiseGit连接github.com”一文,现在学习在linux下编程,在网上找了点资料,配置在linux下使用github,将过 ...

  10. Django——如何处理请求(URL配置和视图)

    URLconfig—— 为了绑定视图函数和URL,我们使用URLconf. URLconf 就像是 Django 所支撑网站的目录. 它的本质是 URL 模式以及要为该 URL 模式调用的视图函数之间 ...