首页 > 解决方案 > 来自美丽汤的 CSV 数据在所有内容前面显示 b 或 \n

问题描述

当我导出到 CSV 文件中的行显示“b”或“\n”不确定需要修复什么时,我刚开始使用 python 和漂亮的汤出现问题。

如果代码草率,我深表歉意我对这一切仍然很陌生

from bs4 import BeautifulSoup
import requests
import csv

source = requests.get ('https://www.shopdisney.com/uniquely-disney/parks-inspired/walt-disney-world-50th-collection/').text
soup = BeautifulSoup(source, 'html.parser')

file = open ('Disney50th.csv', 'w')
writer = csv.writer(file)

#write header rows
writer.writerow(['Item Name', 'Item Price', 'Item Link'])

products = soup.find_all('div', class_="product__tile")

for item_info in products:
    
    price = item_info.find('span', class_='value')
    name = item_info.find('a', class_= "product__tile_link")
    link = item_info.find('a', class_= "product__tile_link")

    p = price.attrs['content']
    n = name.get_text('title')
    l = link.attrs['href']

    print ("Item Name =", n, '\n' "Item Link =", l, '\n' "Item Price =",p)

    writer.writerow([n.encode('utf-8'), p.encode('utf-8'), l.encode('utf-8')])

file.close

CSV 显示如下:

编辑器中的 CSV 图像

感谢您提前提供任何帮助。

标签: pythoncsvbeautifulsoup

解决方案


前面b的东西是因为.encode('utf-8')你做的时候

writer.writerow([n.encode('utf-8'), p.encode('utf-8'), l.encode('utf-8')])

这会将这些值从str对象转换为bytes. 您应该能够简单地删除它们并改用以下内容:

writer.writerow([n, p, l])

至于空格 and \n,那是因为您要添加的字符串中包含这些字符。您可以像这样删除它们str.strip

writer.writerow([n.strip(), p.strip(), l.strip()])

或等效地:

writer.writerow([x.strip() for x in (n, p, l)])

推荐阅读