官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/

  使用前需要先安装模块,并安装解析器

pip install beautifulsoup4
pip install lxml
pip install html5lib

  安装完成后倒入模块

from bs4 import BeautifulSoup

  选择解析器创建对象

html = urllib.request.urlopen(url).read()
bs = BeautifulSoup(html,'lxml')

  格式化输出

print(bs.prettify())

  

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

1.Tag:Tag有很多方法和属性,最重要的属性为name和attributes

>>> soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
>>> tag = soup.b
>>> type(tag)
<class 'bs4.element.Tag'>

  name属性:每个tag都有自己的名字,通过 .name 来获取:

>>> tag.name
'b' #如果改变了tag的name,那将影响所有通过当前Beautiful Soup对象生成的HTML文档
>>> tag.name = "blockquote"
>>> tag
<blockquote class="boldest">Extremely bold</blockquote>

  attributes属性:获取标签内的属性

#可以直接通过.attrs获取
>>> tag.attrs
{'class': ['boldest']} #也可以以字典的方式获取
>>> tag['class']
['boldest'] #tag的属性可以被添加,删除或修改
>>> tag['class'] = 'verybold' #修改
>>> tag['id'] = 1 #添加
>>> tag
<blockquote class="verybold" id="1">Extremely bold</blockquote>
>>> del tag['class'] #删除
>>> del tag['id'] #删除
>>> tag
<blockquote>Extremely bold</blockquote>  

2.NavigableString:获取标签内的字符串

>>> soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
>>> tag = soup.b
>>> tag.string
'Extremely bold'
>>> type(tag.string)
<class 'bs4.element.NavigableString'>

tag中包含的字符串不能编辑,但是可以被替换成其它的字符串,用 replace_with() 方法

>>> tag.string.replace_with("No longer bold")
'Extremely bold'
>>> tag
<blockquote>No longer bold</blockquote>

3.BeautifulSoup

BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag对象,它支持 遍历文档树 和 搜索文档树 中描述的大部分的方法.

因为 BeautifulSoup 对象并不是真正的HTML或XML的tag,所以它没有name和attribute属性.但有时查看它的 .name 属性是很方便的,所以 BeautifulSoup 对象包含了一个值为 “[document]” 的特殊属性 .name

>>> soup.name
'[document]'

4.comment:注释部分

Tag , NavigableString , BeautifulSoup 几乎覆盖了html和xml中的所有内容,但是还有一些特殊对象.容易让人担心的内容是文档的注释部分

>>> markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
>>> soup = BeautifulSoup(markup)
>>> comment = soup.b.string
>>> type(comment)
<class 'bs4.element.Comment'>
>>> comment
'Hey, buddy. Want to buy a used parser?'

  

findall方法:搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件,find方法相当于find_all(limit=1)

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

name 参数:

可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉.简单的用法如下

soup.find_all("title")
# [<title>The Dormouse's story</title>]

keyword 参数:

  如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性.

soup.find_all(id='link2')
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

  如果属性名和关键字重复,可以在属性名后加上_,例如class_

soup.find_all('div',class_="p12" )

  如果传入 href 参数,Beautiful Soup会搜索每个tag的”href”属性:

soup.find_all(href=re.compile("elsie"))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

  下面的例子在文档树中查找所有包含 id 属性的tag,无论 id 的值是什么

soup.find_all(id=True)
# [<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>]

  使用多个指定名字的参数可以同时过滤tag的多个属性

soup.find_all(href=re.compile("elsie"), id='link1')
# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]

  有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性

data_soup = BeautifulSoup('<div data-foo="value">foo!</div>')
data_soup.find_all(data-foo="value")
# SyntaxError: keyword can't be an expression

  但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag:

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

text 参数:

  通过 text 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, text参数接受 字符串 , 正则表达式 , 列表, True . 看例子:  

soup.find_all(text="Elsie")
# [u'Elsie'] soup.find_all(text=["Tillie", "Elsie", "Lacie"])
# [u'Elsie', u'Lacie', u'Tillie'] soup.find_all(text=re.compile("Dormouse"))
[u"The Dormouse's story", u"The Dormouse's story"] def is_the_only_string_within_a_tag(s):
""Return True if this string is the only child of its parent tag.""
return (s == s.parent.string) soup.find_all(text=is_the_only_string_within_a_tag)
# [u"The Dormouse's story", u"The Dormouse's story", u'Elsie', u'Lacie', u'Tillie', u'...']

limit 参数:

  find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.

  文档树中有3个tag符合搜索条件,但结果只返回了2个,因为我们限制了返回数量:

soup.find_all("a", limit=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>]

  

  

 

查找文档中所有的<b>标签  

soup.find_all('b')

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

import re
for tag in soup.find_all(re.compile("^b")):
print(tag.name)

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

soup.find_all(["a", "b"])

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

for tag in soup.find_all(True):
print(tag.name)
# html
# head
# title
# body
# p
# b
# p
# a
# a
# a
# p

python beautiful soup的更多相关文章

  1. 推荐一些python Beautiful Soup学习网址

    前言:这几天忙着写分析报告,实在没精力去研究django,虽然抽时间去看了几遍中文文档,还是等实际实践后写几篇操作文章吧! 正文:以下是本人前段时间学习bs4库找的一些网址,在学习的可以参考下,有点多 ...

  2. Python Beautiful Soup学习之HTML标签补全功能

    Beautiful Soup是一个非常流行的Python模块.该模块可以解析网页,并提供定位内容的便捷接口. 使用下面两个命令安装: pip install beautifulsoup4 或者 sud ...

  3. python beautiful soup库的超详细用法

    原文地址https://blog.csdn.net/love666666shen/article/details/77512353 参考文章https://cuiqingcai.com/1319.ht ...

  4. Python Beautiful Soup 解析库的使用

    Beautiful Soup 借助网页的结构和属性等特性来解析网页,这样就可以省去复杂的正则表达式的编写. Beautiful Soup是Python的一个HTML或XML的解析库. 1.解析器 解析 ...

  5. python Beautiful Soup的使用

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

  6. (17)python Beautiful Soup 4.6

    一.安装 1.登陆官网:https://www.crummy.com/software/BeautifulSoup/ 2.下载 3.解压 4.安装 cmd找到文件路径,运行 setup.py buil ...

  7. Python Beautiful Soup 4

    Beautiful Soup 是一个灵活方便的网页解析库,利用它不用编写正则表达式即可方便地提取的网页信息 官方文档:https://www.crummy.com/software/Beautiful ...

  8. python Beautiful Soup 采集it books pdf,免费下载

    http://www.allitebooks.org/ 是我见过最良心的网站,所有书籍免费下载 周末无聊,尝试采集此站所有Pdf书籍. 采用技术 python3.5 Beautiful soup 分享 ...

  9. Python Beautiful Soup库

    Beautiful Soup库 Beautiful Soup库:https://www.crummy.com/software/BeautifulSoup/ 安装Beautiful Soup: 使用B ...

随机推荐

  1. MongoDB的介绍安装与基本使用

    MongoDB的介绍安装 关于MongoDB的介绍于安装可参考:https://www.cnblogs.com/DragonFire/p/9135630.html 除了官网下载,可以下载他人下载好分享 ...

  2. Netty源码分析 (二)----- ServerBootstrap

    BootStrap在netty的应用程序中负责引导服务器和客户端.netty包含了两种不同类型的引导: 1. 使用服务器的ServerBootStrap,用于接受客户端的连接以及为已接受的连接创建子通 ...

  3. 【selenium】- webdriver常见元素定位(下)

    本文由小编根据慕课网视频亲自整理,转载请注明出处和作者. 1.table 表格如下: 使用firebug查看: 代码实现: 1)显示出表格所有内容 2)显示表格某个特定的数值 自动化测试框架: 关键字 ...

  4. gym/102059/problem/I. Game on Plane SG函数做博弈

    传送门: 题意: 给定一个正n边形的点.双方轮流连点成线,要求所画的线不能与之前的线相交.当某个人连成一个回路,这个人就输了.问先手必胜还是后手必胜. 思路: SG函数,因为一条线相当于把图劈成了两半 ...

  5. AOJ-2249-Road Construction-dijkstra-最小花费

    Road Construction 题意:在一个无向图中,每条边上有建设的花费和路径的长度,要求求得,在保持每个点到1号点最小距离不变的情况下,求最小的总花费: 思路:用dijkstra 找出每个点的 ...

  6. Codeforces Round #379 (Div. 2) E. Anton and Tree 缩点 树的直径

    传送门 题意: 这道题说的是在一颗有两种颜色的树上,每操作一个节点,可以改变这个节点颜色和相邻同色节点的颜色.问最少操作次数,使得树上颜色相同. 思路: 先缩点,把相同的颜色的相邻节点缩在一起.再求出 ...

  7. 江苏 徐州邀请赛 icpc B Array dp 滚动数组模板

    题目 题目描述 JSZKC is the captain of the lala team. There are N girls in the lala team. And their height ...

  8. Atcoder C - Closed Rooms(思维+bfs)

    题目链接:http://agc014.contest.atcoder.jp/tasks/agc014_c 题意:略. 题解:第一遍bfs找到所有可以走的点并标记步数,看一下最少几步到达所有没锁的点,然 ...

  9. SpringCloud Feign 之 Fallback初体验

    SpringCloud Feign 之 Fallback初体验 在微服务框架SpringCloud中,Feign是其中非常重要且常用的组件.Feign是声明式,模板化的HTTP客户端,可以帮助我们更方 ...

  10. 逆向破解之160个CrackMe —— 030

    CrackMe —— 030 160 CrackMe 是比较适合新手学习逆向破解的CrackMe的一个集合一共160个待逆向破解的程序 CrackMe:它们都是一些公开给别人尝试破解的小程序,制作 c ...