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

BeautifulSoup中strings与stripped_strings方法的区别是什么?

BeautifulSoup中strings与stripped_strings方法的区别

两者的核心差异体现在对空白字符的处理逻辑上:

  • strings方法:返回目标标签下的所有字符串,完全保留原始内容中的空白字符(包括换行、空格、制表符等)
  • stripped_strings方法:返回目标标签下的字符串时,会自动过滤掉每个字符串两端的空白字符,同时会直接忽略仅由空白字符组成的字符串

示例代码

import requests
from bs4 import BeautifulSoup
url = "https://codewithharry.com"
r = requests.get(url)
htmlcontent = r.content
soup = BeautifulSoup(htmlcontent, 'html.parser')

tags = soup.find(id="imgpreview2")

# 使用strings方法
for item in tags.strings:
    print(item)

# 使用stripped_strings方法
for item in tags.stripped_strings:
    print(item)

效果说明

运行上述代码后:

  • strings的输出会包含大量空白行或带首尾空格的文本,完全还原HTML中的原始字符串格式
  • stripped_strings的输出则只保留有效文本内容,所有字符串的首尾空白都被清理,纯空白的内容会被直接跳过

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:04:49