技术标签: 爬虫 bs4基本使用方法 Beautifu Soup库
Beautifu Soup库一个非常优秀的Python第三方库,可以很好地对HTML进行解析并且提取其中的信息。主要负责解析、遍历、维护“标签树”。
以管理员命令运行cmd=>pip install beautifulsoup4
这里注意后面有个4,这是最新的版本。详细可以参考Beautiful Soup的官网
>>> import requests
>>> r = requests.get('http://python123.io/ws/demo.html')
>>> r.text
'...` # 这里省略了内容
>>> demo = r.text
>>> from bs4 import BeautifulSoup # 这个导入需要注意
>>> soup = BeautifulSoup(demo,'html.parser') # 可以用help(BeautifulSop)查看帮助文档
>>> print(soup.prettify())
`...` # 这里省略了内容
Beautiful Soup库就是一个工具,可以从被标记的信息中识别出来标记信息,从而精准的提取你需要的信息。
Beautiful Soup库,也叫beautifulsoup4 或bs4,约定引用方式如下,即主要是用BeautifulSoup类
# 第一种用的最为频繁
from bs4 import BeautifulSoup
# 第二种
import bs4
BeautifulSoup类,BeautifulSoup对应一个HTML/XML文档的全部内容。
接着测试文档实践
任何存在于HTML语法中的标签都可以用soup.访问获得,当HTML文档中存在多个相同对应内容时,soup.返回第一个。
>>> soup.title
<title>This is a python demo page</title>
>>> tag = soup.a
>>> print(tag)
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
每个tag都有自己的名字,通过.name获取,字符串类型。
>>> soup.a.name
'a'
>>> soup.a.parent.name
'p'
>>> soup.a.parent.parent.name
'body'
一个可以有0或多个属性,返回一个字典,属于字典类型。
>>> tag = soup.a
>>> tag.attrs
{
'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}
>>> tag.attrs['class'] # 根据字典的键,获取相应的值
['py1']
>>> tag.attrs['href']
'http://www.icourse163.org/course/BIT-268001'
>>> type(tag.attrs) # 查看属性类型
<class 'dict'>
>>> type(tag)
<class 'bs4.element.Tag'>
NavigableString可以跨越多个层次,前提是只有一个字符串子串,多余一个子串则也返回None.
help文档里面解释是:
string
| Convenience property to get the single string within this tag.
|
| :Return: If this tag has a single string child, return value
| is that string. If this tag has no children, or more than one
| child, return value is None. If this tag has one child tag,
| return value is the ‘string’ attribute of the child tag,
| recursively.
>>> soup.a
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
>>> soup.a.string
'Basic Python'
>>> soup.p # 可以跨越多个层次
<p class="title"><b>The demo python introduces several python courses.</b></p>
>>> soup.p.string
'The demo python introduces several python courses.'
>>> type(soup.p.string)
<class 'bs4.element.NavigableString'>
Comment是一种特殊类型。
>>> newsoup = BeautifulSoup("<b><!--This is a comment--></b><p>This is not a comment</P>","html.parser")
>>> newsoup.b.string
'This is a comment'
>>> type(newsoup.b.string)
<class 'bs4.element.Comment'> # 注释类型
>>> newsoup.p.string
'This is not a comment'
>>> type(newsoup.p.string)
<class 'bs4.element.NavigableString'> # 非注释的字符串类型
官方help文档,常与字符串的split()方法联用来分割得到需要的部分。
text
| Get all child strings, concatenated using the given separator.
>>> soup.h1.text
'\n\n 中国中车 (601766)\n \n已收盘 2019-01-23 \xa015:01:28\n \n'
基于bs4库的HTML内容遍历方法主要分为三种:下行遍历、上行遍历、平行遍历。
标签树的下行遍历的三个属性:
# 遍历儿子节点
for child in soup.body.children:
print(child)
# 遍历子孙节点
for child in soup.body.descendants:
print(child)
实例演示:
>>> soup.head # 查看标签
<head><title>This is a python demo page</title></head>
>>> soup.head.contents # 查看head标签的内容,注意这里返回的是一个列表,所以可以对返回到列表执行列表操作
[<title>This is a python demo page</title>]
>>> soup.body.contents # 获得body标签的内容列表
['\n', <p class="title"><b>The demo python introduces several python courses.</b></p>, '\n', <p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>, '\n']
>>> len(soup.body.contents) # 获取列表的元素个数,注意这里的'\n'也算一个元素
5
>>> soup.body.contents[1] # 查看列表的第二个元素
<p class="title"><b>The demo python introduces several python courses.</b></p>
标签树的上行遍历主要包含两个属性:
>>> soup.title.parent
<head><title>This is a python demo page</title></head>
>>> soup.html.parent
<html><head><title>This is a python demo page</title></head>
<body>
<p class="title"><b>The demo python introduces several python courses.</b></p>
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>
</body></html>
>>> soup.parent # soup的父亲是空的
# 对Soup.a标签的所有父辈标签名字进行打印
>>> for parent in soup.a.parents: # 标签树的上行代码遍历
if parent is None: # 因为会遍历到最上面的soup,但是soup没有标签名,所以要区分对待
print(parent)
else:
print(parent.name)
p
body
html
[document]
标签树的平行遍历有四个属性:
# 遍历后续平行节点
for sibling in soup.a.next_sibling:
print(sibling)
# 遍历前续平行节点
for sibling in soup.a.previous_sibling:
print(sibling)
实例:
>>> soup.a.next_sibling # 注意这里得到的不是标签,而是字符串,所以需要做判断处理
' and '
>>> soup.a.next_sibling.next_sibling
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
>>> soup.a.previous_sibling
'Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n'
>>> soup.a.previous_sibling.previous_sibling
>>> soup.a.parent
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>
prettify()方法能够让HTML的内容更加友好的显示出来便于我们分析网页,从而发现规律。
.prettify()为HTML文本<>及其内容增加’\n’
.prettify()可用于标签,方法:.prettify()
bs4库将任何HTML输入都变成utf‐8编码
Python 3.x默认支持编码是utf‐8,解析无障碍
实例如下:
>>> soup.prettify()
'<html>\n <head>\n <title>\n This is a python demo page\n </title>\n </head>\n <body>\n <p class="title">\n <b>\n The demo python introduces several python courses.\n </b>\n </p>\n <p class="course">\n Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\n <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">\n Basic Python\n </a>\n and\n <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">\n Advanced Python\n </a>\n .\n </p>\n </body>\n</html>'
>>> print(soup.prettify())
<html>
<head>
<title>
This is a python demo page
</title>
</head>
<body>
<p class="title">
<b>
The demo python introduces several python courses.
</b>
</p>
<p class="course">
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
Basic Python
</a>
and
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
Advanced Python
</a>
.
</p>
</body>
</html>
<>.find_all(name, attrs, recursive, string, **kwargs)——返回一个列表类型,存储查找的结果
# 1. name: 对标签名称的检索字符串
>>> soup.find_all('a') # 注意返回的是一个列表
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all(['a','b']) # 传入一个列表,实现同时检索出列表里面两个或者多个标签的内容
[<b>The demo python introduces several python courses.</b>, <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> for tag in soup.find_all(True):
print(tag.name)
html
head
title
body
p
b
p
a
a
# 实现同时检索出b标签和包含b字符的body标签,需要引入正则表达式re模块
>>> import re
>>> for tag in soup.find_all(re.compile('b')):
print(tag.name)
body
b
# 2. attrs: 对标签属性值的检索字符串,可标注属性检索
>>> soup.find_all('p','course')
[<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>]
>>> soup.find_all(id = 'link1')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>]
>>> soup.find_all(id='link') # 需要完全匹配,所以匹配不到link,返回空列表
[]
>>> soup.find_all(id=re.compile('link')) # 通过正则表达式实现部分匹配
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
# 3. recursive: 是否对子孙全部检索,默认True
>>> soup.find_all('a') # 返回包括子孙节点在内的所有‘a'标签的内容,下面是查到到两个
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all('a',recursive=False) # 可以看到在soup这个平行节点中,没有找到a标签,所以a标签在soup的子孙节点
[]
# 4. string: <>…</>中字符串区域的检索字符串
>>> soup.find_all(string = 'Basic Python') # 完全匹配检索Basic Python
['Basic Python']
>>> soup.find_all(string = re.compile("python")) # 使用re模块的正则表达式实现部分匹配,所以re和find_all()结合使用,功能强大
['This is a python demo page', 'The demo python introduces several python courses.']
注意:
(…) 等价于.find_all(…)
soup(…) 等价于soup.find_all(…)
扩展方法:
后记:
我从本硕药学零基础转行计算机,自学路上,走过很多弯路,也庆幸自己喜欢记笔记,把知识点进行总结,帮助自己成功实现转行。
2020下半年进入职场,深感自己的不足,所以2021年给自己定了个计划,每日学一技,日积月累,厚积薄发。
如果你想和我一起交流学习,欢迎大家关注我的微信公众号每日学一技
,扫描下方二维码或者搜索每日学一技
关注。
这个公众号主要是分享和记录自己每日的技术学习,不定期整理子类分享,主要涉及 C – > Python – > Java,计算机基础知识,机器学习,职场技能等,简单说就是一句话,成长的见证!
文章浏览阅读1.1w次,点赞7次,收藏34次。vue-grid-layout的使用、实例、遇到的问题和解决方案_vue-grid-layout
文章浏览阅读218次。然后连接一个数据源,就会在下面自动产生一个添加附件的组件。把这个控件复制粘贴到页面里,就可以单独使用来上传了。插入一个“编辑”窗体。_powerapps点击按钮上传附件
文章浏览阅读264次。(1) Abstraction (抽象)(2) Polymorphism (多态)(3) Inheritance (继承)(4) Encapsulation (封装)_"object(cnofd[\"ofdrender\"])十条"
文章浏览阅读133次。删除node_modules,重新npm install看是否成功。在 package.json 文件中的 scripts 中加入。修改你的第三方库的bug等。然后目录会多出一个目录文件。_修改 node_modules
文章浏览阅读883次。【代码】【】kali--password:su的 Authentication failure问题,&sudo passwd root输入密码时Sorry, try again._password: su: authentication failure
文章浏览阅读1w次,点赞13次,收藏97次。整理5个优秀的微信小程序开源项目。收集了微信小程序开发过程中会使用到的资料、问题以及第三方组件库。_微信小程序开源模板
文章浏览阅读128次。Centos7最简搭建NFS服务器_centos7 搭建nfs server
文章浏览阅读1.2k次,点赞2次,收藏3次。前言mybatis在持久层框架中还是比较火的,一般项目都是基于ssm。虽然mybatis可以直接在xml中通过SQL语句操作数据库,很是灵活。但正其操作都要通过SQL语句进行,就必须写大量的xml文件,很是麻烦。mybatis-plus就很好的解决了这个问题。..._mybaitis-plus ruledataobjectattributemapper' and 'com.picc.rule.management.d
文章浏览阅读325次。EECE 1080C / Programming for ECESummer 2022Laboratory 4: Global Functions PracticePlagiarism will not be tolerated:Topics covered:function creation and call statements (emphasis on global functions)Objective:To practice program development b_eece1080c
文章浏览阅读53次。被同机房早就1年前就学过的东西我现在才学,wtcl。设要求的数为\(x\)。设当前处理到第\(k\)个同余式,设\(M = LCM ^ {k - 1} _ {i - 1}\) ,前\(k - 1\)个的通解就是\(x + i * M\)。那么其实第\(k\)个来说,其实就是求一个\(y\)使得\(x + y * M ≡ a_k(mod b_k)\)转化一下就是\(y * M ...
文章浏览阅读1.3k次。首先,问题是如何出现的?晚上复查代码,发现一个activity没有调用自己的ondestroy方法我表示非常的费解,于是我检查了下代码。发现再finish代码之后接了如下代码finish();System.exit(0);//这就是罪魁祸首为什么这样写会出现问题System.exit(0);////看一下函数的原型public static void exit (int code)//Added ..._android 手动杀死app,activity不执行ondestroy
文章浏览阅读894次。Q: SylixOS 版权是什么形式, 是否分为<开发版税>和<运行时版税>.A: SylixOS 是开源并免费的操作系统, 支持 BSD/GPL 协议(GPL 版本暂未确定). 没有任何的运行时版税. 您可以用她来做任何 您喜欢做的项目. 也可以修改 SylixOS 的源代码, 不需要支付任何费用. 当然笔者希望您可以将使用 SylixOS 开发的项目 (不需要开源)或对 SylixOS 源码的修改及时告知笔者.需要指出: SylixOS 本身仅是笔者用来提升自己水平而开发的_select函数 导致堆栈溢出 sylixos