您的位置:宽带测速网 > 编程知识 > BeautifulSoup中怎么获取字符串内容

BeautifulSoup中怎么获取字符串内容

2025-07-04 09:35来源:互联网 [ ]

在BeautifulSoup中,要获取标签内的字符串内容可以使用.string属性或.get_text()方法来实现。例如:

from bs4 import BeautifulSouphtml = """<html><body><p>这是一个段落</p></body></html>"""soup = BeautifulSoup(html, 'html.parser')p_tag = soup.find('p')# 使用.string属性获取字符串内容content = p_tag.stringprint(content)# 使用get_text()方法获取字符串内容content = p_tag.get_text()print(content)

以上代码会输出:

这是一个段落这是一个段落