查找 HTML 中的所有标签和属性

Finding all tags and attributes in a HTML

我是新手,第一次看 HTML 代码。对于我的研究,我需要知道网页中标签和属性的数量。

我查看了各种解析器,发现 Beautiful Soup 是最受欢迎的解析器之一。以下代码(摘自Parsing HTML using Python)展示了解析文件的方法:

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen('http://www.google.com/')
soup = BeautifulSoup(page)

x = soup.body.find('div', attrs={'class' : 'container'}).text

我发现 find_all 非常有用,但需要一个参数才能找到一些东西。

谁能指导我如何知道 html 页面中所有标签和属性 的 数量?

google 开发者工具可以在这方面提供帮助吗?

如果您不带任何参数调用 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(//@*)"))

如果您想要所有标签和属性的计数:

sum(len(ele.attrs) + 1 for ele in BeautifulSoup(page).find_all())