Finding all tags and attributes in a HTML

我的未来我决定 提交于 2019-12-06 08:09:07

If you would call find_all() without any arguments, it would find all elements on a page recursively. Demo:

>>> 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 showed you how to count elements and attributes via BeautifulSoup. In addition to it, here is how to do the same with lxml.html:

from lxml.html import fromstring

root = fromstring(data)
print int(root.xpath("count(//*)")) + int(root.xpath("count(//@*)"))

As a bonus, I've made a simple benchmark demonstrating that the latter approach is much faster (on my machine, with my setup and without specifying a parser which would make BeautifulSoup use lxml under-the-hood etc..a lot of things can affect the results, but anyway):

$ 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

where test.py contains:

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(//@*)"))

If you want the count of all tags and attrs:

sum(len(ele.attrs) + 1 for ele in BeautifulSoup(page).find_all())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!