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
相关产品推荐
相关产品推荐

