python - 为什么replace()、re.sub() 或strip() 不能处理这个字符串?

标签 python beautifulsoup replace trim strip

我正在使用 BeautifulSoup 从网页获取结果。我已将数据对象转换为字符串,但无法修剪它。

我有以下字符串:

text = '\n\n\n 此产品不可用。\n\n'

我尝试了三个选项来开始删除换行符:

  1. string=text.replace('\n','')

  2. string=text.strip('\n')

import re
string = re.sub('\n','', text)

为什么在所有情况下字符串输出仍然与文本相同?我还没明白其中的逻辑。

有人知道发生了什么事吗?

更新: 整个编程文本(如果允许重现):

import requests
from bs4 import BeautifulSoup
import re

resp = requests.get('https://soysuper.com/p/granola-con-avena-y-frutos-rojos-kellogg-s-special-k-320-g-320-g', headers={'User-Agent':'Chrome/44.0.2403.157','Accept-Language': 'es-ES, es;q=0.5'})
soup = BeautifulSoup(resp.content.decode('UTF-8'),'html.parser')

data = [element.text for element in soup.find_all("section", {"class": "display display--coco"})]

text=str(data)

#option1
string=text.replace('\n',' ')
#option2
string=text.strip('\n')
#option3
string = re.sub('\n','', text)

print(string)

最佳答案

只需使用.getText(strip=True)

方法如下:

import requests
from bs4 import BeautifulSoup

resp = requests.get('https://soysuper.com/p/granola-con-avena-y-frutos-rojos-kellogg-s-special-k-320-g-320-g', headers={'User-Agent':'Chrome/44.0.2403.157','Accept-Language': 'es-ES, es;q=0.5'})
soup = BeautifulSoup(resp.content.decode('UTF-8'),'html.parser')

data = [element.getText(strip=True) for element in soup.find_all("section", {"class": "display display--coco"})]
print(data)

输出:

['Este producto no está disponible en ningún supermercado online.']

关于python - 为什么replace()、re.sub() 或strip() 不能处理这个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74589213/

相关文章:

r - 复杂情况下如何正确使用 `replace`?

python - 在 Python 2.7.2 中设置端口以与 Arduino Uno 一起使用

python - 抓取站点为链接返回不同的 href

python - 为什么在浏览器开发工具和 BeautifulSoap/Postman 中获取不同的数据?

javascript - 使用 Javascript 将字符串添加到 CSS 代码

javascript - 替换文本,然后将其替换回来

python - PyMySQL 是否支持 SELECT...FOR UPDATE?

python - 按天过滤 Pandas 数据框

python - 合并和采样两个 Pandas 时间序列

python - 使用 beautiful soup 从 <td> 标签中提取正确格式的文本(中间有空格)