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

时间:2015-06-08 19:51:16

标签: python html xml-parsing beautifulsoup html-parsing

我是新手,第一次看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页面中所有标签和属性的数量吗?

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

2 个答案:

答案 0 :(得分:3)

如果你想要所有标签和attrs的计数:

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

答案 1 :(得分:2)

如果您在没有任何参数的情况下调用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(//@*)"))