一开始我们就举了这样的例子,使用find
或者是find_all
对html
的代码进行搜索,为了弄清Beautiful Soup
中的关系,我们来看看这样的一段代码,其中会产生一些疑问,通过疑问的排查过程,能够更进一步的了解Beautiful Soup
。
看如下的代码:
_#!/usr/bin/python
#coding=utf-8
_**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="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>
</body>
</html>
"""
soup = BeautifulSoup(html, "lxml")
print 'soup',type(soup)
body_tag = soup.find('body')
print 'body_tag',type(body_tag)
a_tag = body_tag.find('a')
print 'a_tag',type(a_tag)
a_list = body_tag.find_all('a')
print 'a_list',type(a_list)
输出的结果如下:
Connected to pydev debugger (build 172.3968.37)
soup <class 'bs4.BeautifulSoup'>
body_tag <class 'bs4.element.Tag'>
a_tag <class 'bs4.element.Tag'>
a_list <class 'bs4.element.ResultSet'>
可以看出,soup
是 bs4.BeautifulSoup
类,他有一个函数为find
,返回的结果是 bs4.element.Tag
类,同时这个bs4.element.Tag
类也有一个函数为find
,好像bs4.BeautifulSoup
和 bs4.element.Tag
好像有什么关联一样,进一步的来了解这两个类,我们使用help
来看看。
>>> help(BeautifulSoup)
Help on class BeautifulSoup in module bs4:
class BeautifulSoup(bs4.element.Tag)
...
发现了class BeautifulSoup(bs4.element.Tag)
说明 bs4.element.Tag
为BeautifulSoup
的父类,bs4.element.Tag
有德属性,BeautifulSoup
都会拥有的。这是很关键的一个联系,bs4.element.Tag
通过find
后返回的是自己也就是bs4.element.Tag
,这样就可以一直find
下去,因为他们都有同一个 函数find
。
我们再来看一下 find_all
,他返回的结果为bs4.element.ResultSet
,这个bs4.element.ResultSet
是什么东西呢?通过同样的方法,我们会发现bs4.element.ResultSet
其实是一个list
,list
中的每个元素还是bs4.element.Tag
,这样的话还是可以使用find
的。必须理清这几个之前的关系,后面处理起来就非常方便了。
通过上面的分析以后,我们发现重点是bs4.element.Tag
,需要清楚bs4.element.Tag
的各个属性,这是Beautiful Soup
的关键。