python - 来自美丽汤的 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 显示如下:
感谢您提前提供任何帮助。
解决方案
前面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)])
推荐阅读
- java - 如何使用 Spring-Boot 在 Eclipse 中修复 'org.hibernate.id.IdentifierGenerationException: Unknown integer data type for ids: java.lang.String'
- forms - 在 Laravel 结果中提交表单到 404
- angular - 如何在没有 ngx-translate-messageformat-compiler 插件的情况下在 ngx-translate 中使用复数
- f# - TypeProvider 未能从 Expression 添加方法
- javascript - 如何按代码对多个数组进行分组然后求和?
- laravel - Laravel 验证,如果另一个字段为 0,则该字段应为 1,反之亦然
- python-3.7 - 如何在 python 中使用 GDAL 从各个地图计算栅格平均值/平均值?
- c# - 如何将 2 个列表合并为 1 个列表,以便在 c# 中将其排序在一起?
- android - 如何在活动中更改 Toolbar 和 BottomNavigationBar 主题
- rest - 如何使用 Dynamics 365 REST API 定义具有“本地选项集”属性的实体