使用Beautiful Soup
对网页进行解析,需要根据网页的结构找到自己需要的关键信息,在找分析网页结构和找出关键信息就经常用到的两个函数为find
和find_all
。
前面我们已经知道,find
和find_all
是有区别的,主要的区别是,find
的结果是返回一个的对象,而
find_all
返回的是一个的对象,
中是一个
的链表。
find
和find_all
的用法基本上没有什么区别,介绍一个find
的使用就能够推广到find_all
的用法。
find
的原型为:
find( name , attrs , recursive , text , **kwargs )
name
也就是html
中的标签,如下使用,还是用到之前的数据:
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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="/lacie" class="sister" >Lacie</a> and
<a href="/tillie" class="sister" >Tillie</a>;
and they lived at the bottom of a well.</p>
</body>
</html>
"""
soup = BeautifulSoup(html, "lxml")
body_tag = (name='body')
print body_tag
输出的结果为:
<body>
<p class="title" name="dromouse"><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="/lacie" >Lacie</a> and
<a class="sister" href="/tillie" >Tillie</a>;
and they lived at the bottom of a well.</p>
</body>
找到了标签名为body
的第一段html
。
如果采用的是
(name='p')
会是怎样的结果呢? 因为html
代码中有多个的p
标签?find
的时候,如果有多个标签的话会返回最先找到的第一个标签。也就是
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
find
和find_all
同样支持 正则表达式
查找,如找出name
中含有 a
或者是p
的tag
:
import re
tags = soup.find_all(name=('a|p'))
for tag in tags:
print tag
输出的结果会是什么呢?
<head><title>The Dormouse's story</title></head>
<p class="title" name="dromouse"><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="/lacie" >Lacie</a> and
<a class="sister" href="/tillie" >Tillie</a>;
and they lived at the bottom of a well.</p>
<a class="sister" href="/lacie" >Lacie</a>
<a class="sister" href="/tillie" >Tillie</a>
在使用name
还是无法容易的找出我们需要的tag
时,这时候可以结合上attrs
的查找方式。
attrs
需要我们给出的值为 字典形式的数据,如下找出class="title"
的tag
:
tags = soup.find_all(name=('a|p'),attrs={'class':'title'})
for tag in tags:
print tag
输出的结果为:
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
使用 text
进行查找:
tags = soup.find_all(name=('a|p'),text='Lacie')
for tag in tags:
print tag
输出的结果如下:
<a class="sister" href="/lacie" >Lacie</a>
同样的可以使用[]
数组进行查找:
tags = soup.find_all(name=('a|p'),text=['Lacie','Tillie'])
for tag in tags:
print tag
值得注意的是,所有的查找方式都支持正则表达式
和 数组查找
。