Python Beautiful Soup模块使用教程详解
作者:Thunderclap_ 发布时间:2021-07-21 16:00:10
标签:Python,Beautiful,Soup
一、模块简介
Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间.
二、方法利用
1、引入模块
# 引入
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" rel="external nofollow" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" 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_doc, 'html.parser')
四种解析器
2、几个简单的浏览结构化数据的方法
#获取Tag,通俗点就是HTML中的一个个标签
#获取Tag,通俗点就是HTML中的一个个标签
soup.title # 获取整个title标签字段:<title>The Dormouse's story</title>
soup.title.name # 获取title标签名称 :title
soup.title.parent.name # 获取 title 的父级标签名称:head
soup.p # 获取第一个p标签字段:<p class="title"><b>The Dormouse's story</b></p>
soup.p['class'] # 获取第一个p中class属性值:title
soup.p.get('class') # 等价于上面
soup.a # 获取第一个a标签字段
soup.find_all('a') # 获取所有a标签字段
soup.find(id="link3") # 获取属性id值为link3的字段
soup.a['class'] = "newClass" # 可以对这些属性和内容等等进行修改
del bs.a['class'] # 还可以对这个属性进行删除
soup.find('a').get('id') # 获取class值为story的a标签中id属性的值
soup.title.string # 获取title标签的值 :The Dormouse's story
三、具体利用
1、获取拥有指定属性的标签
方法一:获取单个属性
soup.find_all('div',id="even") # 获取所有id=even属性的div标签
soup.find_all('div',attrs={'id':"even"}) # 效果同上
方法二:
soup.find_all('div',id="even",class_="square") # 获取所有id=even并且class=square属性的div标签
soup.find_all('div',attrs={"id":"even","class":"square"}) # 效果同上
2、获取标签的属性值
方法一:通过下标方式提取
for link in soup.find_all('a'):
print(link['href']) //等同于 print(link.get('href'))
方法二:利用attrs参数提取
for link in soup.find_all('a'):
print(link.attrs['href'])
3、获取标签中的内容
divs = soup.find_all('div') # 获取所有的div标签
for div in divs: # 循环遍历div中的每一个div
a = div.find_all('a')[0] # 查找div标签中的第一个a标签
print(a.string) # 输出a标签中的内容
如果结果没有正确显示,可以转换为list列表
4、stripped_strings
去除\n换行符等其他内容 stripped_strings
divs = soup.find_all('div')
for div in divs:
infos = list(div.stripped_strings) # 去掉空格换行等
bring(infos)
四、输出
1、格式化输出prettify()
prettify() 方法将Beautiful Soup的文档树格式化后以Unicode编码输出,每个XML/HTML标签都独占一行
markup = '<a href="http://example.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)
soup.prettify()
# '<html>\n <head>\n </head>\n <body>\n <a href="http://example.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >\n...'
print(soup.prettify())
# <html>
# <head>
# </head>
# <body>
# <a href="http://example.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
# I linked to
# <i>
# example.com
# </i>
# </a>
# </body>
# </html>
2、get_text()
如果只想得到tag中包含的文本内容,那么可以调用 get_text() 方法,这个方法获取到tag中包含的所有文版内容包括子孙tag中的内容,并将结果作为Unicode字符串返回:
markup = '<a href="http://example.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >\nI linked to <i>example.com</i>\n</a>'
soup = BeautifulSoup(markup)
soup.get_text()
u'\nI linked to example.com\n'
soup.i.get_text()
u'example.com'
来源:https://blog.csdn.net/Thunderclap_/article/details/128948135
0
投稿
猜你喜欢
- 有这样的情形,django个人头像在model中是:class UserProfile(AbstractUser): ""
- 模糊数据库指能够处理模糊数据的数据库。一般的数据库都是以二直逻辑和精确的数据工具为基础的,不能表示许多模糊不清的事情。随着模糊数学理论体系的
- 故事的开始:.count()假设你有一个Notification Model类,保存的主要是所有的站内通知:class Notificati
- PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单
- 前言ThinkPHP,是为了简化企业级应用开发和敏捷WEB应用开发而诞生的开源轻量级PHP框架。随着框架代码量的增加,一些潜在的威胁也逐渐暴
- Oracle数据库升级也并非简单的事,这篇文章对Oracle那点事做了较详细的介绍:Oracle数据库升级或数据迁移方法研究我还属于Orac
- 目标网址:https://www.baidu.com/要获取的内容:链接分析:从下图可以看出只需要获取关键字,再构建就可以了。完整代码:im
- 简介:1.霍夫变换(Hough Transform) 霍夫变换是图像处理中从图像中识别几何形状的基本方法之一,应用很广泛,也有很多改进算法。
- 矩阵增加行np.row_stack() 与 np.column_stack()import numpy as npa = np.array(
- 看代码吧~import numpy as np a = np.array([[1,1,1],[2,2,2],[3,3,3], [4,4,4]
- 本文研究的主要是Python的端口扫描程序,具体实例代码如下。先来看看第一个端口扫描程序代码,获取本机的IP和端口号:import sock
- 昨天在看别人blog的时候发现DW有这么一个东西。叫做代码片断。我们可以将常用的css定义写一个代码片断。保存在DW中,作为公用库。当再次写
- 本文作为属性篇的最后一篇文章, 将讲述HTML和CSS的关键—盒子模型(Box model). 理解Box model的关键便是margin
- 我们知道,dropout一般都在训练的时候使用,那么测试的时候如何也开启dropout呢?在pytorch中,网络有train和eval两种
- 在互联网出现之前,“抄”很不方便,一是“源”少,而是发布渠道少;而在互联网出现之后,“抄”变得很简单,铺天盖地的“源”源源不断,发布渠道也数
- 网页链接:https://www.huya.com/g/4079 这里的主要步骤其实还是和我们之前分析的一样,如下图所示:这里再简单带大家看
- Batch Normalization和Dropout是深度学习模型中常用的结构。但BN和dropout在训练和测试时使用却不相同。Batc
- 本文通过问答的开式来解答在mysql在命名用过程中所遇到的常见问题。谁能连接,从那儿连接?你可以允许一个用户从特定的或一系列主机连接。有一个
- 列表(元组)基本操作符回顾len()函数在列表与元组上的使用示例如下:names = ['Neo', 'Lily
- 本文实例为大家分享了python实现简单俄罗斯方块游戏的具体代码,供大家参考,具体内容如下import pygame,sys,random,