“Beautiful Soup, so rich and green,
Waiting in a hot tureen!
Who for such dainties would not stoop?
Soup of the evening, beautiful Soup! ”
—Alice in Wonderland
Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库。它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式。
我使用的pip安装:
pip install beautifulsoup4
from bs4 import BeautifulSoup as 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>"""
bsObj=bs(html_doc)
##使用prettify方法使得打印出来的bsObj有按标准的缩进
print(bsObj.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>
当我们想要查找HTML中的某些内容的时候:
1、想找到HTML中的某个标签及其值
##这里的tag指所有的标签名
bsObj.tag
##返回标签的父标签名
bsObj.tag.parent.name
##返回p标签的class
bsObj.p["class"]
2、想找到整个HTML的链接
bsObj.find_all('a')
bsObj.findAll('a')
将所有的a标签返回,如果我们只是单纯地想知道那些链接是什么
for link in bsObj.find_all('a'):
print(link.get('href'))
get()感觉和get_text()有些相像,不过get_text()只是会返回这个标签的文字内容而不是我们想要的数据