写在前面:目前本人正在自学Python,渣新手,如果有什么问题,也是纯粹个人理解,如有错误,还是欢迎各位大佬指正。
自学爬虫过程中,本人第一个练手项目爬取了k站的图片,使用正则表达式匹配图片时会出现其他一些我不需要的内容,
于是正则写成了这样
reg = r'class="directlink largeimg" href="(.+?.jpg)"'
个人认为肯定是有问题的,不过好在满足了要求成功爬取了k站的图片,接下来想弄些复杂的数据,于是看上了豆瓣,以本人目前的正则水平,肯定是无法满足需要的,于是百度时发现了可以使用BeautifulSoup库来实现html的解析。
首先表扬BeautifulSoup是一个自带官方中文文档的第三方库,详细学习请自行点击链接,接下来的内容为本人学习的记录,以及在学习中遇到的问题。
接下来简单介绍下使用方法
- 安装
本人因工作原因开发环境为:日语64位win7+pycharm
点击底部的Terminal,打开控制台输入:pip install beautifulsoup4
等待安装完成
- 使用
以官方文档中提供的html文档为例
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" 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>
"""
使用BeautifulSoup解析html
#官方文档上没有加features参数,但实测不加时会有个警告
soup=BeautifulSoup(html_doc,features="html.parser")
未加features参数时的警告:
UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.
The code that caused this warning is on line 17 of the file C:/Users/Administrator/PycharmProjects/untitled/venv/study/beautifulsoap4.py. To get rid of this warning, pass the additional argument 'features="html.parser"' to the BeautifulSoup constructor.
soup=BeautifulSoup(html_doc)
问题为没有指明html的解释器,BeautifulSoup支持许多html的解释器,这里贴一个官方文档中的图,展示各种解释器的优缺点
如果需要使用其他的解释器需要安装后使用,同样打开控制台
pip install lxml
pip install html5lib
对需要的解释器进行安装后方可使用。
那接下来就默认使用Python的标准库来解析html
- 格式化输出html
print(soup.prettify())
- 获取某一个标签的所有内容,例如获取<title>标签的所有内容
print(soup.title)
- 获取某一标签的标签名(这一个在看到的时候陷入迷茫,不知道有什么作用)
print(soup.title.name)
- 获取某一标签中的内容
print(soup.title.string)
- 获取某一标签的父标签,例如获取title标签的父标签
print(soup.title.parent.name)
- 获取某一标签的class属性
print(soup.p["class"])
-
获取a标签的href属性值
print(soup.a["href"])
- 获取所有a标签
print(soup.find_all('a'))
- 获取所有a标签中的链接
for link in soup.find_all('a'):
print(link.get('href'))
通过limit参数设定返回满足条件的数量
- find_all limit参数
print(soup.find_all('a',limit=2))
因为参数设置只返回两条符合条件的数据,当需要返回的数据只有一条时可以直接使用find()方法。
目前这些知识点已经满足本人目前开发需要,如果有需要后面还会继续学习并更新的。
当然有需要的再次给大家推荐官方中文文档