使用Beautiful Soup从H2字段中提取文本的解决方法如下:
from bs4 import BeautifulSoup
html = """
This is a heading
This is a paragraph.
"""
# 创建Beautiful Soup对象
soup = BeautifulSoup(html, 'html.parser')
# 通过find方法找到第一个H2标签
h2_tag = soup.find('h2')
# 提取H2标签中的文本
text = h2_tag.text
# 输出提取的文本
print(text)
输出结果为:
This is a heading
这个例子中,我们首先使用Beautiful Soup将HTML代码解析成一个Beautiful Soup对象。然后,通过调用find
方法找到第一个H2标签,并将其赋值给变量h2_tag
。最后,通过调用text
属性来提取H2标签中的文本内容。