使用BeautifulSoup爬取文本数组的问题可以通过以下代码示例来解决:
from bs4 import BeautifulSoup
html = """
Text 1
Text 2
Text 3
"""
soup = BeautifulSoup(html, 'html.parser')
text_array = []
# 使用find_all方法找到所有符合条件的p标签
p_tags = soup.find_all('p', class_='text')
# 遍历p_tags,提取文本内容并添加到text_array数组中
for p in p_tags:
text_array.append(p.text)
print(text_array)
输出结果为:
['Text 1', 'Text 2', 'Text 3']
在这个示例中,我们首先使用BeautifulSoup将HTML字符串转换为BeautifulSoup对象。然后使用find_all方法找到所有class为"text"的p标签,并将它们存储在p_tags数组中。然后我们遍历p_tags数组,提取每个p标签的文本内容,并将其添加到text_array数组中。最后打印出text_array数组的值。