[英]Why this replace(), re.sub() or strip() do not work with this string?
我正在使用 BeautifulSoup 從網頁獲取結果。 我已將數據 object 轉換為字符串,但無法對其進行修整。
我有以下字符串:
text = '\n\n\n This product is not available.\n \n'
我嘗試了三個選項來開始刪除換行符:
string=text.replace('\n','')
string=text.strip('\n')
import re
string = re.sub('\n','', text)
為什么字符串output 在所有情況下都與文本相同? 我還沒有理解其中的邏輯。
有人知道發生了什么事嗎?
更新:整個編程文本,以防它允許重現:
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)
Output:
['Este producto no está disponible en ningún supermercado online.']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.