1.BeautifulSoup简介

BeautifulSoup是一个可以从HTML或XML文件中提取数据的python库;它能够通过转换器实现惯用的文档导航、查找、修改文档的方式。

BeautifulSoup是一个基于re开发的解析库,可以提供一些强大的解析功能;使用BeautifulSoup能够提高提取数据的效率与爬虫开发效率。

2.BeautifulSoup总览

构建文档树

BeautifulSoup进行文档解析是基于文档树结构来实现的,而文档树则是由BeautifulSoup中的四个数据对象构建而成的。

文档树对象 描述
Tag 标签; 访问方式:soup.tag;属性:tag.name(标签名),tag.attrs(标签属性)
Navigable String 可遍历字符串; 访问方式:soup.tag.string
BeautifulSoup 文档全部内容,可作为Tag对象看待; 属性:soup.name(标签名),soup.attrs(标签属性)
Comment 标签内字符串的注释; 访问方式:soup.tag.string
import lxml
import requests
from bs4 import BeautifulSouphtml =  """
<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" 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>
"""#1、BeautifulSoup对象
soup = BeautifulSoup(html,'lxml')
print(type(soup))#2、Tag对象
print(soup.head,'\n')
print(soup.head.name,'\n')
print(soup.head.attrs,'\n')
print(type(soup.head))#3、Navigable String对象
print(soup.title.string,'\n')
print(type(soup.title.string))#4、Comment对象
print(soup.a.string,'\n')
print(type(soup.a.string))#5、结构化输出soup对象
print(soup.prettify())

遍历文档树

BeautifulSoup之所以将文档转为树型结构,是因为树型结构更便于对内容的遍历提取。

向下遍历方法 描述
tag.contents tag标签子节点
tag.children tag标签子节点,用于循环遍历子节点
tag.descendants tag标签子孙节点,用于循环遍历子孙节点
向上遍历方法 描述
tag.parent tag标签父节点
tag.parents tag标签先辈节点,用于循环遍历先别节点
平行遍历方法 描述
tag.next_sibling tag标签下一兄弟节点
tag.previous_sibling tag标签上一兄弟节点
tag.next_siblings tag标签后续全部兄弟节点
tag.previous_siblings tag标签前序全部兄弟节点
import requests
import lxml
import json
from bs4 import BeautifulSouphtml =  """
<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" 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>
"""soup = BeautifulSoup(html,'html.parser')#1、向下遍历
print(soup.p.contents)
print(list(soup.p.children))
print(list(soup.p.descendants))#2、向上遍历
print(soup.p.parent.name,'\n')
for i in soup.p.parents:print(i.name)#3、平行遍历
print('a_next:',soup.a.next_sibling)
for i in soup.a.next_siblings:print('a_nexts:',i)
print('a_previous:',soup.a.previous_sibling)
for i in soup.a.previous_siblings:print('a_previouss:',i)

搜索文档树

BeautifulSoup提供了许多搜索方法,能够便捷地获取我们需要的内容。

遍历方法 描述
soup.find_all( ) 查找所有符合条件的标签,返回列表数据
soup.find 查找符合条件的第一个个标签,返回字符串数据
soup.tag.find_parents() 检索tag标签所有先辈节点,返回列表数据
soup.tag.find_parent() 检索tag标签父节点,返回字符串数据
soup.tag.find_next_siblings() 检索tag标签所有后续节点,返回列表数据
soup.tag.find_next_sibling() 检索tag标签下一节点,返回字符串数据
soup.tag.find_previous_siblings() 检索tag标签所有前序节点,返回列表数据
soup.tag.find_previous_sibling() 检索tag标签上一节点,返回字符串数据

需要注意的是,因为class是python的保留关键字,若要匹配标签内class的属性,需要特殊的方法,有以下两种:

  • 在attrs属性用字典的方式进行参数传递
  • BeautifulSoup自带的特别关键字class_
import requests
import lxml
import json
from bs4 import BeautifulSouphtml =  """
<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" 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>
"""soup = BeautifulSoup(html,'html.parser')#1、find_all( )
print(soup.find_all('a'))  #检索标签名
print(soup.find_all('a',id='link1')) #检索属性值
print(soup.find_all('a',class_='sister'))
print(soup.find_all(text=['Elsie','Lacie']))#2、find( )
print(soup.find('a'))
print(soup.find(id='link2'))#3 、向上检索
print(soup.p.find_parent().name)
for i in soup.title.find_parents():print(i.name)#4、平行检索
print(soup.head.find_next_sibling().name)
for i in soup.head.find_next_siblings():print(i.name)
print(soup.title.find_previous_sibling())
for i in soup.title.find_previous_siblings():print(i.name)

CSS选择器

BeautifulSoup选择器支持绝大部分的CSS选择器,在Tag或BeautifulSoup对象的.select( )方法中传入字符串参数,即可使用CSS选择器找到Tag。

常用HTML标签:

HTML标题:<h> </h>
HTML段落:<p> </p>
HTML链接:<a href='httts://www.baidu.com/'> this is a link </a>
HTML图像:<img src='Ai-code.jpg',width='104',height='144' />
HTML表格:<table> </table>
HTML列表:<ul> </ul>
HTML块:<div> </div>
import requests
import lxml
import json
from bs4 import BeautifulSouphtml =  """
<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" 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>
"""soup = BeautifulSoup(html,'html.parser')print('标签查找:',soup.select('a'))
print('属性查找:',soup.select('a[id="link1"]'))
print('类名查找:',soup.select('.sister'))
print('id查找:',soup.select('#link1'))
print('组合查找:',soup.select('p #link1'))

爬取图片实例

import requests
from bs4 import BeautifulSoup
import osdef getUrl(url):try:read = requests.get(url)  read.raise_for_status()   read.encoding = read.apparent_encoding  return read.text    except:return "连接失败!"def getPic(html):soup = BeautifulSoup(html, "html.parser")all_img = soup.find('ul').find_all('img') for img in all_img:src = img['src']  img_url = srcprint(img_url)root = "F:/Pic/"   path = root + img_url.split('/')[-1]  print(path)try:if not os.path.exists(root):  os.mkdir(root)if not os.path.exists(path):read = requests.get(img_url)with open(path, "wb")as f:f.write(read.content)f.close()print("文件保存成功!")else:print("文件已存在!")except:print("文件爬取失败!")if __name__ == '__main__':html_url=getUrl("https://findicons.com/search/nature")getPic(html_url)

Python BeautifulSoup简介相关推荐

  1. python BeautifulSoup的使用

    1.BeautifulSoup简介 Beautiful Soup 提供一些简单的.python 式的函数用来处理导航.搜索.修改分析树等功能.它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为 ...

  2. BeautifulSoup简介

    BeautifulSoup简介 介绍 lxml 只会局部遍历,而Beautiful Soup 是基于HTML DOM的,会载入整个文档,解析整个DOM树,因此时间和内存开销都会大很多,所以性能要低于l ...

  3. python beautifulsoup抓取网页内容_利用Python和Beautiful Soup抓取网页内容

    利用Python和Beautiful Soup抓取网页内容 Posted on 2012-08-09 00:08 SamWei 阅读(381) 评论(1) 编辑 收藏 Python 3中提供了url打 ...

  4. 《从问题到程序:用Python学编程和计算》——1.2 Python语言简介

    本节书摘来自华章计算机<从问题到程序:用Python学编程和计算>一书中的第1章,第1.2节,作者 裘宗燕,更多章节内容可以访问云栖社区"华章计算机"公众号查看. 1. ...

  5. Python beautifulsoup爬取小说

    Python beautifulsoup爬取小说 提前准备好需要的库文件,命令行输入以下命令 pip install requests pip install bs4 pip install lxml ...

  6. Python列表简介

    Python列表简介 什么是列表 #普通的变量定义形式 tom ='Tom' jack ='Jack' john ='John'pet1 ='cat' pet2 ='dog' pet3 ='bird' ...

  7. Python编程简介

    Python编程简介 2011年06月23日 NOTE: The following is a short tutorial about python program, for Chinese rea ...

  8. Python+beautifulsoup+requests 爬取网易新闻评论

    前段时间在看处理数据相关的书籍,实践中需要一些网上评论的文本数据集,所以想到爬取网易新闻底下的评论.本来想着Python+beautifulsoup(解析)+requests(抓取),最后存储在txt ...

  9. 大数据教程【05.01】--Python 数据分析简介

    更多信息请关注WX搜索GZH:XiaoBaiGPT Python数据分析简介 本教程将介绍如何使用Python进行大数据分析.Python是一种功能强大且易于使用的编程语言,具备丰富的数据分析库和工具 ...

最新文章

  1. python 签名计算 请求参数签名
  2. LUOGU P2827 蚯蚓 (noip 2016)
  3. 真正理解 git fetch, git pull 以及 FETCH_HEAD
  4. 【Linux】在Deepin v20或UOS20下运行MC我的世界
  5. html6与html5的区别,XHTML和HTML5的区别
  6. 服务的心跳机制与断线重连,Netty底层是怎么实现的?
  7. Jsp基本page指令、注释、方法声明,书写规范及注意事项
  8. 6. Controller
  9. 银行会计凭证粗略整理
  10. 自然码双拼输入法的辅助码编写问题
  11. 2021国赛新大陆物联网Ubuntu系统维护(中职)
  12. 国外有哪些知名的游戏资讯网站或博客?
  13. python协程处理海量文件_Python使用asyncio和run-In-Executor线程池处理多个文件的同时下载,python,协程,加,runinexecutor...
  14. 网易云web安全工程师第一天
  15. EasyExcel锁定指定单元格 禁止表格复制
  16. VB如何自动保存_发酵鱼饵与果酸、VB小药的搭配,这才是夏季钓大鱼的必杀配方!...
  17. 十一、高斯混合模型(Gaussian Mixed Model, GMM)
  18. java封装统一返回结果工具类(CommonResultUtils)
  19. 潮汕古韵之都,这次目的地——潮州
  20. 关于revision 的cover letter

热门文章

  1. ae 创建图像等高线 蒙版_「PS软件」工具使用,图层蒙版与橡皮擦的应用分析
  2. Choco-slover的使用
  3. C++实现JPEG格式图片解析(附代码)
  4. java 监听客户端的退出_Java socket 服务端如何监控客户端异常关闭?
  5. elementui实现上传视频功能+预览
  6. 黑盒测试(什么是黑盒测试 黑盒测试的优缺点 黑盒测试中的测试方法)
  7. 【Python】《Python语言程序设计》(嵩天 、黄天羽 、礼欣)测验单项选择题答案与解析合辑
  8. Tails OS 让你实现隐形上网!
  9. vue.js devtools
  10. 双足竞走机器人的意义_基于STM32双足竞步机器人的研究与设计