HTMLParser模块简介
我们使用urllib模块进行HTTP请求获取到的是整个网页的HTML,但是我们往往只需要其中一部分对我们有用的内容。这时我们就可以使用HTMLParser模块来帮助我们处理HTML。
HTMLParser是Python内置的专门用来解析HTML的模块。利用HTMLParser,我们可以分析出一段HTML里面的标签、数据等,是一种处理HTML的简便途径。
基于BS库的网页源码整理
假设我们在网上爬取了下列源码
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>
"""
我们想要继续对其中的数据进行分析,但爬取后的html代码段格式较为混乱,那么我们可以使用BeautifulSoup中的 preettitf()函数进行 对所爬取的代码进行初步的分行整理。
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())
整理后的结果为:
<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 class="sister" href="http://example.com/elsie" id="link1">
Elsie
</a>
,
<a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</a>
and
<a class="sister" href="http://example.com/tillie" id="link3">
Tillie
</a>
;
and they lived at the bottom of a well.
</p>
<p class="story">
...
</p>
</body>
</html>
整理后可以更清楚的看到源码的每层结构和片段归属。