Python爬虫工具 BeautifulSoup 使用详解

2023-06-0516:58:28后端程序开发Comments696 views字数 3453阅读模式

一、模块简介

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找、修改文档的方式。Beautiful Soup会帮你节省工作时间.文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

二、方法利用

1、安装beautifulsoup文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

pip install beautifulsoup4

2、引入模块

from bs4 import beautifulsoup

3、选择解析器解析指定内容

soup=beautifulsoup(解析内容,解析器)

常用解析器:html.parser,lxml,xml,html5lib文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

有时候需要安装安装解析器:比如pip3 install lxml文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

BeautifulSoup默认支持Python的标准HTML解析库,但是它也支持一些第三方的解析库:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

解析器使用方法优势劣势
Python标准库BeautifulSoup(markup,文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

 "html.parser")

Python的内置标准库文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

执行速度适中文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

文档容错能力强

Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差
lxml HTML 解析器BeautifulSoup文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

(markup, "lxml")文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

速度快文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

文档容错能力强

需要安装C语言库
lxml XML 解析器BeautifulSoup文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

(markup, ["lxml-xml"])文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

BeautifulSoup文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

(markup, "xml")

速度快文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

唯一支持XML的解析器

需要安装C语言库
html5libBeautifulSou文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

p(markup, "html5lib")文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

最好的容错性文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

以浏览器的方式解析文档文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

生成HTML5格式的文档

速度慢文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

不依赖外部扩展

4、几个简单的浏览结构化数据的方法

#获取Tag,通俗点就是HTML中的一个个标签文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

#获取Tag,通俗点就是HTML中的一个个标签soup.title                    # 获取整个title标签字段:<title>The Dormouse's story</title>soup.title.name               # 获取title标签名称  :titlesoup.title.parent.name        # 获取 title 的父级标签名称:headsoup.p                        # 获取第一个p标签字段:<p class="title"><b>The Dormouse's story</b></p>soup.p['class']               # 获取第一个p中class属性值:titlesoup.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文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

divs = soup.find_all('div')for div in divs:    infos = list(div.stripped_strings)        # 去掉空格换行等    bring(infos)

四、输出

1、格式化输出prettify()

prettify() 方法将Beautiful Soup的文档树格式化后以Unicode编码输出,每个XML/HTML标签都独占一行文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.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()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

如果只想得到tag中包含的文本内容,那么可以调用 get_text() 方法,这个方法获取到tag中包含的所有文版内容包括子孙tag中的内容,并将结果作为Unicode字符串返回:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

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()'\nI linked to example.com\n'soup.i.get_text()'example.com'

参考文档文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html

https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/44933.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/44933.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定