You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用bs4提取单个p标签中的指定文本内容

使用BeautifulSoup提取

标签中的指定文本

针对你给出的HTML结构,有几种简单的方法可以提取出"Great Clips"这个文本:

方法1:直接获取第一个文本节点并清理空白

通过contents属性获取

标签下的所有子节点,第一个子节点就是目标文本,最后用strip()去除多余的空白字符:

from bs4 import BeautifulSoup

html = '''<p class="text-base font-medium text-gray-700 w-1/2" xpath="1">
                        Great Clips

                                                    <br><span class="text-blue-600 font-normal text-sm">Request Info</span>
                                            </p>'''
soup = BeautifulSoup(html, 'html.parser')
p_tag = soup.find('p', class_='text-base font-medium text-gray-700 w-1/2')
# 获取第一个文本节点并清理空白
target_text = p_tag.contents[0].strip()
print(target_text)  # 输出: Great Clips

方法2:利用stripped_strings迭代器

stripped_strings会返回标签下所有去除空白后的文本内容,取第一个元素即可:

from bs4 import BeautifulSoup

html = '''<p class="text-base font-medium text-gray-700 w-1/2" xpath="1">
                        Great Clips

                                                    <br><span class="text-blue-600 font-normal text-sm">Request Info</span>
                                            </p>'''
soup = BeautifulSoup(html, 'html.parser')
p_tag = soup.find('p', class_='text-base font-medium text-gray-700 w-1/2')
# 取stripped_strings的第一个元素
target_text = next(p_tag.stripped_strings)
print(target_text)  # 输出: Great Clips

方法3:提取父标签的直接文本(不包含子元素文本)

使用find(text=True, recursive=False)获取

标签自身的直接文本,再清理空白:

from bs4 import BeautifulSoup

html = '''<p class="text-base font-medium text-gray-700 w-1/2" xpath="1">
                        Great Clips

                                                    <br><span class="text-blue-600 font-normal text-sm">Request Info</span>
                                            </p>'''
soup = BeautifulSoup(html, 'html.parser')
p_tag = soup.find('p', class_='text-base font-medium text-gray-700 w-1/2')
# 获取直接文本并清理
target_text = p_tag.find(text=True, recursive=False).strip()
print(target_text)  # 输出: Great Clips

内容的提问来源于stack exchange,提问作者muchamadfaiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 00:45:46