在HTML中查找所有标签和属性 - python

我是新手,并且是第一次阅读HTML代码。为了进行研究,我需要知道网页中标签和属性的数量。

我查看了各种解析器,发现“美丽汤”是最喜欢的解析器之一。以下代码(取自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开发人员工具可以在这方面提供帮助吗?

python大神给出的解决方案

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