上几篇笔记记录了BeautifulSoup对文档的搜索功能。
find_all()方法,加上合适的过滤器,几乎能满足网页爬虫的需要。
这篇文章先把搜索文档最后的CSS选择器讲完,然后简单地介绍修改文档树和最后的结果输出。
下篇文章详细介绍bs4编码和输出格式。
bs4文档就看完了。
1 CSS selectors
Beautiful Soup supports the most commonly-used CSS selectors. Just pass a string into the .select() method of a Tag object or the BeautifulSoup object itself.
这里有一篇文章:CSS 选择器参考手册http://www.w3school.com.cn/cssref/css_selectors.asp
下面用到的语法都能在这篇文章中找到。
接着用爱丽丝文档作为例子:
>>> 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>
"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html_doc,"html.parser")
1.1 find tags
>>> soup.select('p')
[<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