Python 使用Beauty Soup获取所有HTML标记

Python 使用Beauty Soup获取所有HTML标记,python,html,beautifulsoup,Python,Html,Beautifulsoup,我正在尝试从Beauty soup获取所有html标记的列表 我看到了find all,但在搜索之前我必须知道标签的名称 如果有像这样的文本 html = """<div>something</div> <div>something else</div> <div class='magical'>hi there</div> <p>ok</p>""" html=“”什么 别的 你好 好的 我怎样才

我正在尝试从Beauty soup获取所有html标记的列表

我看到了find all,但在搜索之前我必须知道标签的名称

如果有像这样的文本

html = """<div>something</div>
<div>something else</div>
<div class='magical'>hi there</div>
<p>ok</p>"""
html=“”什么
别的
你好
好的
我怎样才能得到这样的列表

list_of_tags = ["<div>", "<div>", "<div class='magical'>", "<p>"]
标签列表=[“”,“”,“”,“”]

我知道如何使用正则表达式实现这一点,但我正在尝试学习BS4,您不必指定任何参数来
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>']
>>来自bs4导入组
>>>
>>>html=“”什么
……还有别的吗
…你好
…好的
>>>soup=BeautifulSoup(html,“html.parser”)
>>>[汤中标记的tag.name.find_all()]
[u'div',u'div',u'div',u'p']
>>>[str(tag)表示汤中的标记。find_all()]
['something'、'something'、'hi there'、'好的

']
我想稍后我会为那些发现自己在这里的人分享一个非常类似问题的解决方案

例子 我需要快速找到所有标记,但只需要唯一的值。我将使用Python
calendar
模块进行演示

我们将生成一个html日历,然后对其进行解析,找到所有且仅存在的唯一标记

以下结构与上述结构非常相似,使用集合理解:

>>来自bs4导入组
>>>导入日历
>>>
>>>html_cal=calendar.HTMLCalendar().formatmonth(2020年1月)
>>>set(BeautifulSoup(html_cal,'html.parser')中标记的tag.name.find_all())
{'table','td','th','tr'}
请尝试以下方法--


下面是我用来解析不同HTML和文本文档的有效函数:

def parse_docs(path, format, tags):
    """
    Parse the different files in path, having html or txt format, and extract the text content.
    Returns a list of strings, where every string is a text document content.
    :param path: str
    :param format: str
    :param tags: list
    :return: list
    """

    docs = []
    if format == "html":
        for document in tqdm(get_list_of_files(path)):
            # print(document)
            soup = BeautifulSoup(open(document, encoding='utf-8').read())
            text = '\n'.join([''.join(s.findAll(text=True)) for s in
                              soup.findAll(tags)])  # parse all <p>, <div>, and <h> tags
            docs.append(text)
    else:
        for document in tqdm(get_list_of_files(path)):
            text = open(document, encoding='utf-8').read()
            docs.append(text)
    return docs
def parse_文档(路径、格式、标记):
"""
解析路径中的不同文件,具有html或txt格式,并提取文本内容。
返回字符串列表,其中每个字符串都是文本文档内容。
:参数路径:str
:param格式:str
:参数标记:列表
:return:list
"""
文档=[]
如果格式==“html”:
对于TQM中的文档(获取文件的列表(路径)):
#打印(文件)
soup=BeautifulSoup(打开(文档,编码='utf-8').read())
text='\n'.join([''.join(s.findAll(text=True))用于中的s
soup.findAll(标记)]#解析所有,以及标记
docs.append(文本)
其他:
对于TQM中的文档(获取文件的列表(路径)):
text=open(文档,编码='utf-8')。read()
docs.append(文本)
退货单据

一个简单的调用:
parse_docs('/path/to/folder',html',['p',h',div'])
将返回一个文本字符串列表。

如果您想找到一些特定的html标记,请尝试以下操作:

html = driver.page_source
soup = BeautifulSoup(html)
for tag in soup.find_all(['a',’div’]):  # Mention HTML tag names here.
print (tag.text)
html = driver.page_source
soup = BeautifulSoup(html)
for tag in soup.find_all(['a',’div’]):  # Mention HTML tag names here.
print (tag.text)