如果您不带任何参数调用find_all(),它将递归查找页面上的所有元素。演示:
>>> from bs4 import BeautifulSoup
>>>
>>> data = """
... <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>
... """
>>>
>>> soup = BeautifulSoup(data)
>>> for tag in soup.find_all():
... print tag.name
...
html
head
title
body
p
b
p
a
a
a
p
Padraic 向您展示了如何通过 BeautifulSoup 计算元素和属性。除此之外,这里是如何对lxml.html做同样的事情:
from lxml.html import fromstring
root = fromstring(data)
print int(root.xpath("count(//*)")) + int(root.xpath("count(//@*)"))
作为奖励,我做了一个简单的基准测试,证明后一种方法要快得多(在我的机器上,使用我的设置并且没有指定 would make BeautifulSoup use lxml under-the-hood 等的解析器......很多事情都会影响结果,但无论如何):
$ python -mtimeit -s'import test' 'test.count_bs()'
1000 loops, best of 3: 618 usec per loop
$ python -mtimeit -s'import test' 'test.count_lxml_html()'
10000 loops, best of 3: 114 usec per loop
其中test.py 包含:
from bs4 import BeautifulSoup
from lxml.html import fromstring
data = """
<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>
"""
def count_bs():
return sum(len(ele.attrs) + 1 for ele in BeautifulSoup(data).find_all())
def count_lxml_html():
root = fromstring(data)
return int(root.xpath("count(//*)")) + int(root.xpath("count(//@*)"))