【Python】Beautiful Soup
简介
- Beautiful Soup 对象 我全部使用soup表示;
- Beautiful Soup 简介:
简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。
1、创建Beautiful Soup 对象
1.1 soup.prettify()
from bs4 import BeautifulSoup
html_content = """
<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" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
#使用html5lib 解释器解释html_conten的内容
soup = BeautifulSoup(html_content,"html5lib")
# 格式化输出html
print(soup.prettify())
该方法是将html进行格式化,输出的内容就是格式化后的html代码。

1.2 soup.标签名
# 输出第一个 title 标签
print(soup.title)
#<title>The Dormouse's story</title>
# 输出第一个 p 标签
print(soup.p)
# <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
1.3 soup.标签名.name
# 输出第一个 title 标签的标签名称
print(soup.title.name)
# title
# 输出第一个 p 标签的标签名称
print(soup.p.name)
# p
1.4 soup.标签名.string
# 输出第一个 title 标签的包含内容
print(soup.title.string)
# The Dormouse's story
# 输出第一个 p 标签的包含内容
print(soup.p.string)
# The Dormouse's story
1.5 soup.标签名.parent.name
# 输出第一个 title 标签的父标签的标签名称
print(soup.title.parent.name)
# head
# 输出第一个 title 标签的父标签的标签名称
print(soup.p.parent.name)
# body
1.6 soup.标签名['属性名']
# 输出第一个 p 标签的 class 属性内容
print(soup.p['class'])
# ['title']
# 输出第一个 a 标签的 href 属性内容
print(soup.a['href'])
# http://example.com/elsie
1.7 修改、删除、添加soup的属性
#操作方法与字典一样
# 修改第一个 a 标签的href属性为 http://www.baidu.com/
soup.a['href'] = 'http://www.baidu.com/'
# 给第一个 a 标签添加 name 属性
soup.a['name'] = u'百度'
# 删除第一个 a 标签的 class 属性为
del soup.a['class']
print(soup.a)
#<a href="http://www.baidu.com/" id="link1" name="百度"><!-- Elsie --></a>
1.8 soup.标签名.contents
##输出第一个 p 标签的所有子节点
print(soup.p.contents)
#[<b>The Dormouse's story</b>]
1.9 soup.find()
# 输出第一个 id 属性等于 link3 的 a 标签
print(soup.find(id="link3"))
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
# 输出第一个 a 标签
print(soup.find('a'))
# <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
#查找ID位link2的a标签的文本
find_a = soup.find('a',id='link2')
print(find_a)
# The Dormouse's story
1.10 soup.find_all()
- 得到是一个序列,我们可以是用遍历的方式对其进行输出,可以得到它的相关属性以及文本的值;
# 输出所有的 a 标签,以列表形式显示
# print(soup.find_all('a'))
#[<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>]
# 查找所有的a标签
find_all_a = soup.find_all('a')
print("查找所有的a标签")
for a_tag in find_all_a:
print(a_tag.getText())
print(a_tag.get('href'))
print soup.find_all("a", class_="sister")
# 通过属性进行查找
print soup.find_all("a", attrs={"class": "sister"})
# 通过文本进行查找
print soup.find_all(text="Elsie")
print soup.find_all(text=["Tillie", "Elsie", "Lacie"])
# 限制结果个数
print soup.find_all("a", limit=2)
1.11 get_text()
#获取所有文字内容
print(soup.get_text())
'''
The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
,
Lacie and
Tillie;
and they lived at the bottom of a well.
...
'''
#获取第一个p标签的内容
print(soup.p.get_text())
# The Dormouse's story
1.12 soup.标签名.attrs
# 输出第一个 a 标签的所有属性信息
print(soup.a.attrs)
# {'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}
1.13 正则匹配
# 正则匹配,名字中带有b的标签
for tag in soup.find_all(re.compile(r"b")):
print(tag.name)
"""
body
b
"""
2、四大内置对象
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:
- Tag
- NavigableString
- BeautifulSoup
- Comment
Tag
- Tag 是什么?通俗点讲就是 HTML 中的一个个标签;
- 两个重要的属性,是 name 和 attrs
name
print(soup.name)
# soup 对象本身比较特殊,它的 name 即为 [document],对于其他内部标签,输出的值便为标签本身的名称。
print(soup.a.name)
# a
attrs
print(soup.p.attrs)
#{'class': ['title'], 'name': 'dromouse'}
#在这里,我们把 p 标签的所有属性打印输出了出来,得到的类型是一个字典。
#如果要获取到某个属性的值,我们可以这样:
print(soup.p['name'])
# dromouse
print(soup.p.get('name'))
# dromouse
删除、修改属性
soup.p['class']="newClass"
print (soup.p )
#<p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>
del soup.p['class']
print soup.p
#<p name="dromouse"><b>The Dormouse's story</b></p>
contents[n] 获取第n个节点的内容
head = soup.find('head')
#head = soup.head
#head = soup.contents[0].contents[0]
print head
html = soup.contents[0] # <html> ... </html>
head = html.contents[0] # <head> ... </head>
body = html.contents[1] # <body> ... </body>
2.2 NavigableString
string
- 获取到标签里面的内容
# 获取到第一个p 标签的内容
print(soup.p.string)
2.3 BeautifulSoup
BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性来感受一下
print type(soup.name)
#<type 'unicode'>
print soup.name
# [document]
print (soup.attrs )
#{} 空字典
2.4 Comment
Comment 对象是一个特殊类型的 NavigableString 对象,其实输出的内容仍然不包括注释符号,但是如果不好好处理它,可能会对我们的文本处理造成意想不到的麻烦。
我们找一个带注释的标签
print (soup.a )
#<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
print soup.a.string
#Elsie
print type(soup.a.string)
#<class 'bs4.element.Comment'>
本文参考:[python BeautifulSoup库用法总结
](https://www.cnblogs.com/scios/p/8652760.html)
【Python】Beautiful Soup的更多相关文章
- 【python】Beautiful Soup的使用
1. Beautiful Soup的简介 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据.官方解释如下: Beautiful Soup提供一些简单的.pyt ...
- 【转载】Beautiful Soup库(bs4)入门
转载自:Beautiful Soup库(bs4)入门 该库能够解析HTML和XML 使用Beautiful Soup库: from bs4 import BeautifulSoup impo ...
- 【爬虫】beautiful soup笔记(待填坑)
Beautiful Soup是一个第三方的网页解析的模块.其遵循的接口为Document Tree,将网页解析成为一个树形结构. 其使用步骤如下: 1.创建对象:根据网页的文档字符串 2.搜索节点:名 ...
- 【python】列出http://www.cnblogs.com/xiandedanteng中所有博文的标题
代码: # 列出http://www.cnblogs.com/xiandedanteng中所有博文的标题 from bs4 import BeautifulSoup import requests u ...
- 【Python②】python之首秀
第一个python程序 再次说明:后面所有代码均为Python 3.3.2版本(运行环境:Windows7)编写. 安装配置好python后,我们先来写第一个python程序.打开IDLE (P ...
- 【python】多进程锁multiprocess.Lock
[python]多进程锁multiprocess.Lock 2013-09-13 13:48 11613人阅读 评论(2) 收藏 举报 分类: Python(38) 同步的方法基本与多线程相同. ...
- 【python】SQLAlchemy
来源:廖雪峰 对比:[python]在python中调用mysql 注意连接数据库方式和数据操作方式! 今天发现了个处理数据库的好东西:SQLAlchemy 一般python处理mysql之类的数据库 ...
- 【python】getopt使用
来源:http://blog.chinaunix.net/uid-21566578-id-438233.html 注意对比:[python]argparse模块 作者:limodou版权所有limod ...
- 【Python】如何安装easy_install?
[Python]如何安装easy_install? http://jingyan.baidu.com/article/b907e627e78fe146e7891c25.html easy_instal ...
- 【Python】 零碎知识积累 II
[Python] 零碎知识积累 II ■ 函数的参数默认值在函数定义时确定并保存在内存中,调用函数时不会在内存中新开辟一块空间然后用参数默认值重新赋值,而是单纯地引用这个参数原来的地址.这就带来了一个 ...
随机推荐
- 飞桨paddlespeech语音唤醒推理C实现
上篇(飞桨paddlespeech 语音唤醒初探)初探了paddlespeech下的语音唤醒方案,通过调试也搞清楚了里面的细节.因为是python 下的,不能直接部署,要想在嵌入式上部署需要有C下的推 ...
- 谈谈selenium中的clear后输入内容异常的处理
谈谈selenium中的clear后输入内容异常的处理 案例 在线考试项目的登录:http://124.223.31.21:9097/#/ 代码 from selenium import webdri ...
- C#写一套最全的MySQL帮助类(包括增删改查)
介绍说明:这个帮助类包含了六个主要的方法:ExecuteNonQuery.ExecuteScalar.ExecuteQuery.ExecuteQuery(泛型).Insert.Update和Delet ...
- RateLimiter使用
1.maven依赖 <dependency> <groupId>com.google.guava</groupId> <artifactId>guava ...
- C++ Primer 5th 阅读笔记:前言
机器效率和编程效率 Its focus, and that of its programming community, has widened from looking mostly at machi ...
- mysql 结合python一些日常写法
python sql语句in写法 sql = "SELECT * FROM user WHERE name in ({})".format(','.join(["'%s' ...
- 2023-03-10:YUV420P像素数据编码为JPEG图片,请用go语言实现。
2023-03-10:YUV420P像素数据编码为JPEG图片,请用go语言实现. 答案2023-03-10: 方法一.使用 github.com/moonfdd/ffmpeg-go 库,基于雷霄骅的 ...
- 2020-10-30:给定一个正数数组arr(即数组元素全是正数),找出该数组中,两个元素相减的最大值,其中被减数的下标不小于减数的下标。即求出: maxValue = max{arr[j]-arr[i] and j >= i}?
福哥答案2020-10-30:1.双重遍历法.2.一次遍历法.golang代码如下: package main import "fmt" const INT_MAX = int(^ ...
- docker无法启动,报错grpc: addrConn.createTransport failed to connect to {unix:///run/containerd/containerd.
docker无法启动,报错.k8s的pod镜像加载失败. 解法方法: 删除/var/lib/docker/和/var/lib/containerd/ 这两个文件夹,重起docker服务. 问题完美解决 ...
- 2021-03-28:定义一种数:可以表示成若干(数量>1)连续正数和的数 。比如:5 = 2+3,5就是这样的数 ;12 = 3+4+5,12就是这样的数 。1不是这样的数,因为要求数量大于1个、连续正数和 。2 = 1 + 1,2也不是,因为等号右边不是连续正数 。给定一个参数N,返回是不是可以表示成若干连续正数和的数 。
2021-03-28:定义一种数:可以表示成若干(数量>1)连续正数和的数 .比如:5 = 2+3,5就是这样的数 :12 = 3+4+5,12就是这样的数 .1不是这样的数,因为要求数量大于1 ...