2016-03-19 84 views
4

我想从美丽汤获取所有html标签的列表。获取美丽汤的所有HTML标签

我发现所有,但我必须知道标签的名称,然后再搜索。

如果有文字像

html = """<div>something</div> 
<div>something else</div> 
<div class='magical'>hi there</div> 
<p>ok</p>""" 

我怎么会得到这样

list_of_tags = ["<div>", "<div>", "<div class='magical'>", "<p>"] 

我知道如何使用正则表达式做这样的列表,但我努力学习BS4

回答

13

你不需要指定任何参数到find_all() - 在这种情况下,BeautifulSoup会递归地在树中找到您的每个标签。样品:

>>> from bs4 import BeautifulSoup 
>>> 
>>> html = """<div>something</div> 
... <div>something else</div> 
... <div class='magical'>hi there</div> 
... <p>ok</p>""" 
>>> soup = BeautifulSoup(html, "html.parser") 
>>> [tag.name for tag in soup.find_all()] 
[u'div', u'div', u'div', u'p'] 
>>> [str(tag) for tag in soup.find_all()] 
['<div>something</div>', '<div>something else</div>', '<div class="magical">hi there</div>', '<p>ok</p>']