安装

pip3 install beautifulsoup4

解析库

解析器 使用方法 优势 劣势
Python标准库 BeautifulSoup(markup,'html,parser') Python的内置标准库、执行速度适中、文档容错能力强 Python 2.7.3 or 3.2.2前的版本中文容错能力差
lxml HTML 解析库 BeautifulSoup(markup,'lxml') 速度快、文档容错能力强 需要安装C语言库
lxml XML 解析库 BeautifulSoup(markup,'xml') 速度快、唯一支持XML的解析器 需要安装C语言库
html5lib BeautifulSoup(markup,'xml') 最好的容错性、以浏览器的方式解析文档、生成HTML5格式的文档 速度慢、不依赖外部扩展

基本使用

html = """
<html dir="ltr" lang="en"><head><meta charset="utf-8"/> <title>The Dormouse's story</title> </head><body><p class="title" name="dormouse"> <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" id="link1"> <!-- Elsie --></a><a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well
</p> <p class="story"> ...story go on...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.prettify()

自动补全代码:

<html dir="ltr" lang="en">
<head>
<meta charset="utf-8"/>
<title>
The Dormouse's story
</title>
</head>
<body>
<p class="title" name="dormouse">
<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" id="link1">
<!-- Elsie -->
</a>
<a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</a>
and
<a class="sister" href="http://example.com/tillie" id="link3">
Tillie
</a>
; and they lived at the bottom of a well
</p>
<p class="story">
...story go on...
</p>
</body>
</html>

print(soup.title.string)

输出html的标题:

The Dormouse's story

标签选择器

选择元素

from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.title)
print(type(soup.title))
print(soup.head)
print(soup.p)

输出结果如下:

<title>The Dormouse's story</title>
<class 'bs4.element.Tag'>
<head><meta charset="utf-8"/> <title>The Dormouse's story</title> </head>
<p class="title" name="dormouse"> <b>The Dormouse's story</b></p> #只返回第一个p标签

获取外层标签的名称

from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.title.name)

title

获取内容的属性

from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.p.attrs['name'])
print(soup.p['name'])

两种获取属性名称的方法

dormouse

dormouse

获取内容

from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.b.string)

The Dormouse's story

嵌套选择

 from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.head.title.string)

The Dormouse's story

字节点和子孙节点

html = '''<html dir="ltr" lang="en"><head><meta charset="utf-8"/>  <title>The Dormouse\'s story</title> </head><body><p class="story">Once upon a time there were three little sisters;and their names were\n   <a class="sister" href="http://example.com/elsie" id="link1">   <span>Elsie </span></a><a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;    and they lived at the bottom of a well\n  </p>  <p class="story">   ...story go on...</p>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.p.contents)
 ['Once upon a time there were three little sisters;and their names were\n   ', <a class="sister" href="http://example.com/elsie" id="link1"> <!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, 'and', <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>, ';    and they lived at the bottom of a well\n  ']

children是一个迭代器:

 from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.p.children)
for i,child in enumerate(soup.p.children):
print(i,child)

<list_iterator object at 0x7fe986ba07f0>

0 Once upon a time there were three little sisters;and their names were

1 <a class="sister" href="http://example.com/elsie" id="link1"> <!-- Elsie --></a>

2 <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>

3 and

4 <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

5 ; and they lived at the bottom of a well

 html = '''<html dir="ltr" lang="en"><head><meta charset="utf-8"/>  <title>The Dormouse\'s story</title> </head><body><p class="story">Once upon a time there were three little sisters;and their names were\n   <a class="sister" href="http://example.com/elsie" id="link1">   <span>Elsie </span></a><a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;    and they lived at the bottom of a well\n  </p>  <p class="story">   ...story go on...</p>
... '''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.p.descendants)
for i,child in enumerate(soup.p.descendants):
print(i,child)

孙节点也被输出出来:

<generator object descendants at 0x7fe986c11468>

0 Once upon a time there were three little sisters;and their names were

1 <a class="sister" href="http://example.com/elsie" id="link1"> <span>Elsie </span></a>

2

3 <span>Elsie </span>

4 Elsie

5 <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>

6 Lacie

7 and

8 <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

9 Tillie

10 ; and they lived at the bottom of a well

父节点和祖先节点

 from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.a.parent)

显示结果:

<p class="story">Once upon a time there were three little sisters;and their names were
<a class="sister" href="http://example.com/elsie" id="link1"> <span>Elsie </span></a><a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well
</p>
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(list(enumerate(soup.a.parent)))

显示结果:

[(0, 'Once upon a time there were three little sisters;and their names were\n   '), (1, <a class="sister" href="http://example.com/elsie" id="link1"> <span>Elsie </span></a>), (2, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>), (3, 'and'), (4, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>), (5, ';    and they lived at the bottom of a well\n  ')]

print(list(enumerate(soup.a.parents)))

显示所有结果:最后为源代码跟节点

[(0, <p class="story">Once upon a time there were three little sisters;and their names were
<a class="sister" href="http://example.com/elsie" id="link1"> <span>Elsie </span></a><a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well
</p>), (1, <body><p class="story">Once upon a time there were three little sisters;and their names were
<a class="sister" href="http://example.com/elsie" id="link1"> <span>Elsie </span></a><a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well
</p> <p class="story"> ...story go on...</p>
</body>), (2, <html dir="ltr" lang="en"><head><meta charset="utf-8"/> <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 class="sister" href="http://example.com/elsie" id="link1"> <span>Elsie </span></a><a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well
</p> <p class="story"> ...story go on...</p>
</body></html>), (3, <html dir="ltr" lang="en"><head><meta charset="utf-8"/> <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 class="sister" href="http://example.com/elsie" id="link1"> <span>Elsie </span></a><a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well
</p> <p class="story"> ...story go on...</p>
</body></html>)]

兄弟节点

 from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(list(enumerate(soup.a.next_siblings)))

显示如下:```html

[(0, Lacie), (1, 'and'), (2, Tillie), (3, '; and they lived at the bottom of a well\n ')]

`print(list(enumerate(soup.a.previous_siblings)))`
> `[(0, 'Once upon a time there were three little sisters;and their names were\n ')]` ## 标准选择器
### find_all(name,attrs,recursive,text,**kwargs)
可根据标签名、属性、内容查找文档
#### name
```py
html = """
<div class="panel">
<div class="panel-heading">
<h4>Helllo</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(soup.find_all('ul'))
print(type(soup.find_all('ul')[0]))

显示结果如下:

[

  • Foo
  • Bar
  • Jay

,

  • Foo
  • Bar

]
```
>
```py
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
for ul in soup.find_all('ul'):
print(ul.find_all('li'))
```
显示结果如下
```html
[

  • Foo
  • ,

  • Bar
  • ,

  • Jay
  • ]
    [

  • Foo
  • ,

  • Bar
  • ]
    ```

    attrs

     html = '''
    <div class="panel">\n <div class="panel-heading">\n <h4>Helllo</h4>\n </div>\n <div class="panel-body">\n <ul class="list" id="list-1" name=elements>\n <li class="element">Foo</li>\n <li class="element">Bar</li>\n <li class="element">Jay</li>\n </ul>\n <ul class="list list-small" id="list-2">\n <li class="element">Foo</li>\n <li class="element">Bar</li>\n </ul>\n </div>\n</div>
    '''
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html,'lxml')
    print(soup.find_all(attrs={'id':'list-1'}))
    print(soup.find_all(attrs={'name':'elements'}))

    显示如下:

    [<ul class="list" id="list-1" name="elements">
    <li class="element">Foo</li>
    <li class="element">Bar</li>
    <li class="element">Jay</li>
    </ul>]
    [<ul class="list" id="list-1" name="elements">
    <li class="element">Foo</li>
    <li class="element">Bar</li>
    <li class="element">Jay</li>
    </ul>]

    另外知道ID或Class可以用下列方法查找:

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html,'lxml')
    print(soup.find_all(id='list-1'))
    [<ul class="list" id="list-1" name="elements">
    <li class="element">Foo</li>
    <li class="element">Bar</li>
    <li class="element">Jay</li>
    </ul>]

    print(soup.find_all(class_='element'))

    [<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>, <li class="element">Foo</li>, <li class="element">Bar</li>]

    text

     from bs4 import BeautifulSoup
    soup = BeautifulSoup(html,'lxml')
    print(soup.find_all(text='Foo'))

    ['Foo', 'Foo']

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

    find返回单个元素,find_all返回所有元素

     from bs4 import BeautifulSoup
    soup = BeautifulSoup(html,'lxml')
    print(soup.find('ul'))
    • Foo
    • Bar
    • Jay

    ```

    print(type(soup.find('ul')))

    <class 'bs4.element.Tag'>

    print(type(soup.find('page')))不存在返回结果:

    <class 'NoneType'>

    CSS选择器

    通过select()直接传入CSS选择器即可完成选择

     from bs4 import BeautifulSoup
    soup = BeautifulSoup(html,'lxml')
    print(soup.select('.panel .panel-heading'))
    print(soup.select('ul li'))
    print(soup.select('#list-2 .element'))
    print(soup.select('ul')[0])

    显示结果如下:

    [```html

    Helllo

    ```]

    [<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>, <li class="element">Foo</li>, <li class="element">Bar</li>]
    [<li class="element">Foo</li>, <li class="element">Bar</li>]
    <ul class="list" id="list-1" name="elements">
    <li class="element">Foo</li>
    <li class="element">Bar</li>
    <li class="element">Jay</li>
    </ul>

    遍历的用法:

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html,'lxml')
    for ul in soup.select('ul'):
    print(ul.select('li'))

    显示结果如下:

    [<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>]
    [<li class="element">Foo</li>, <li class="element">Bar</li>]

    获取属性

     from bs4 import  BeautifulSoup
    soup = BeautifulSoup(html,'lxml')
    for ul in soup.select('ul'):
    print(ul['id'])
    print(ul.attrs['id'])

    显示效果如下:

    list-1

    list-1

    list-2

    list-2

    获取内容

     from bs4 import BeautifulSoup
    soup = BeautifulSoup(html,'lxml')
    for li in soup.select('li'):
    print(li.get_text())

    显示结果:

    Foo

    Bar

    Jay

    Foo

    Bar

    总结:

    • 推荐使用lxml解析库,必要时使用html.parser
    • 标签选择筛选功能弱但是速度快
    • 建议使用find()、find_all()查询匹配单个结果或多个结果
    • 如果对CSS选择器书系建议使用select()
    • 记住常用的获取属性和文本值的方法

    Python爬虫系列-BeautifulSoup详解的更多相关文章

    1. Python爬虫系列-Selenium详解

      自动化测试工具,支持多种浏览器.爬虫中主要用来解决JavaScript渲染的问题. 用法讲解 模拟百度搜索网站过程: from selenium import webdriver from selen ...

    2. Python爬虫系列-PyQuery详解

      强大又灵活的网页解析库.如果你觉得正则写起来太麻烦,如果你觉得BeautifulSoup语法太难记,如果你熟悉jQuery的语法,那么PyQuery就是你的最佳选择. 安装 pip3 install ...

    3. python爬虫scrapy项目详解(关注、持续更新)

      python爬虫scrapy项目(一) 爬取目标:腾讯招聘网站(起始url:https://hr.tencent.com/position.php?keywords=&tid=0&st ...

    4. 爬虫系列---selenium详解

      一 安装 pip install Selenium 二 安装驱动 chrome驱动文件:点击下载chromedriver (yueyu下载) 三 配置chromedrive的路径(仅添加环境变量即可) ...

    5. 使用Python爬虫库BeautifulSoup遍历文档树并对标签进行操作详解(新手必学)

      为大家介绍下Python爬虫库BeautifulSoup遍历文档树并对标签进行操作的详细方法与函数下面就是使用Python爬虫库BeautifulSoup对文档树进行遍历并对标签进行操作的实例,都是最 ...

    6. 反爬虫:利用ASP.NET MVC的Filter和缓存(入坑出坑) C#中缓存的使用 C#操作redis WPF 控件库——可拖动选项卡的TabControl 【Bootstrap系列】详解Bootstrap-table AutoFac event 和delegate的分别 常见的异步方式async 和 await C# Task用法 c#源码的执行过程

      反爬虫:利用ASP.NET MVC的Filter和缓存(入坑出坑)   背景介绍: 为了平衡社区成员的贡献和索取,一起帮引入了帮帮币.当用户积分(帮帮点)达到一定数额之后,就会“掉落”一定数量的“帮帮 ...

    7. python 3.x 爬虫基础---Urllib详解

      python 3.x 爬虫基础 python 3.x 爬虫基础---http headers详解 python 3.x 爬虫基础---Urllib详解 前言 爬虫也了解了一段时间了希望在半个月的时间内 ...

    8. 第7.19节 Python中的抽象类详解:abstractmethod、abc与真实子类

      第7.19节 Python中的抽象类详解:abstractmethod.abc与真实子类 一.    引言 前面相关的章节已经介绍过,Python中定义某种类型是以实现了该类型对应的协议为标准的,而不 ...

    9. python之OS模块详解

      python之OS模块详解 ^_^,步入第二个模块世界----->OS 常见函数列表 os.sep:取代操作系统特定的路径分隔符 os.name:指示你正在使用的工作平台.比如对于Windows ...

    随机推荐

    1. CodeForces - 507B - Amr and Pins(计算几何)

      Amr loves Geometry. One day he came up with a very interesting problem. Amr has a circle of radius r ...

    2. Codeforces Round 56-B. Letters Rearranging(思维)

      time limit per test 1 second memory limit per test 256 megabytes input standard input output standar ...

    3. NOI2015品酒大会 后缀数组

      自己尝试敲后缀数组,发现难看(tiao)的不行,于是抄了板子 考虑建出hei以后转化出的问题: 对于一个数组中权值大于等于k的连续部分,求取两个数的方案数和两数积的最大值 (好气啊,可以有负数) 把询 ...

    4. 一篇文章彻底了解Java垃圾收集(GC)机制

      垃圾收集(Garbage Collection ,GC),是一个长久以来就被思考的问题,当考虑GC的时候,我们必须思考3件事情: 哪些内存需要回收? 什么时候回收? 如何回收? 那么在Java中,我们 ...

    5. js window对象属相和方法相关整理资料

      window对象有以下方法: open close alert confirm prompt setTimeout clearTimeout setInterval clearInterval mov ...

    6. java Integer

      Java 中的数据类型分为基本数据类型和引用数据类型 int是基本数据类型,Integer是引用数据类型: Ingeter是int的包装类,int的初值为0,Ingeter的初值为null. 初始化 ...

    7. ssas 为绑定指定的大小太小,导致一个或多个列值被截断

      错误信息:ssas 为绑定指定的大小太小,导致一个或多个列值被截断 如果更改了某个维度或是事实表的字段长度,在处理CUBE时提示此错误,我们要做以下更新: 1.刷新数据源视图. 2.打开多维数据集,查 ...

    8. 时间日期相关:Date类、DateFormat类、Calendar类

      1 Date类 类 Date 表示特定的瞬间,精确到毫秒. 1秒=1000毫秒 毫秒的0点:公元1970年 一月一日,午夜0:00:00 对应的毫秒值就是0 时间和日期的计算,必须依赖毫秒值. Sys ...

    9. 洛谷P2606 [ZJOI2010]排列计数(组合数 dp)

      题意 题目链接 称一个1,2,...,N的排列P1,P2...,Pn是Magic的,当且仅当2<=i<=N时,Pi>Pi/2. 计算1,2,...N的排列中有多少是Magic的,答案 ...

    10. Cannot load JDBC driver class 'com.mysql.jdbc.Driver解决方法

      “Cannot load JDBC driver class 'com.mysql.jdbc.Driver ” 表示没有JDBC连接MySql的驱动包,因此需要手动添加驱动包到WEB-INF目录下的l ...