以下是一个示例代码,用于将所有的标签读入Python的BeautifulSoup库,并将其存入一个数组中:
from bs4 import BeautifulSoup
html = """
Sample Page
This is the first paragraph.
This is the second paragraph.
This is the third paragraph.
"""
soup = BeautifulSoup(html, 'html.parser')
p_tags = soup.find_all('p')
p_list = []
for p in p_tags:
p_list.append(p.text)
print(p_list)
输出结果将是:
['This is the first paragraph.', 'This is the second paragraph.', 'This is the third paragraph.']
在这个示例中,我们首先导入了BeautifulSoup库,然后将要解析的HTML代码存储在一个字符串变量中。接下来,我们使用BeautifulSoup的构造函数创建了一个BeautifulSoup对象,并指定了要使用的解析器(这里使用了默认的HTML解析器)。
然后,我们使用find_all
方法找到所有的标签,并将它们存储在一个列表变量
p_tags
中。
最后,我们创建了一个空列表p_list
,并使用一个循环遍历p_tags
中的每个标签。对于每个标签,我们使用
.text
属性获取其文本内容,并将其添加到p_list
中。
最后,我们打印出p_list
,即包含了所有标签文本内容的数组。