如何修复UnicodeEncodeError:?

2024-05-03 07:51:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从一个本地的网站上删除一些数据。在

import bs4
import os
import requests

from bs4 import BeautifulSoup as soup

os.chdir('E://')
os.makedirs('E://scrappy', exist_ok=True)
myurl = "https://www.example.com"
res = requests.get(myurl)
page = soup(res.content, 'html.parser')
containers = page.findAll("div", {"class": "content-product"})
filename = 'AM4.csv'
f = open(filename, 'w')
headers = 'Motherboard_Name, Price\n'
f.write(headers)

for container in containers:
    Product = container.findAll("div", {"class": "product-title"})
    Motherboard_Name = Product[0].text.strip()
    Kimat = container.findAll("span", {"class": "price"})
    Price = Kimat[0].text
    print('Motherboard_Name' + Motherboard_Name)
    print('Price' + Price)
    f.write(Motherboard_Name + "," + Price.replace(",", "") + "\n")
f.close() print("done")

但是当我运行这个代码时,我得到了一个错误

UnicodeEncodeError:“charmap”编解码器无法对位置45中的字符“\u20b9”进行编码:字符映射到

我该怎么解决这个问题??在

Edit::所以我通过添加encoding=“utf-8”(正如这里提到的python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>)(open(filename,'w',encoding=“utf-8”))修复了unicode错误,但是在csv文件中,在价格前加上了类似(–¹)的字符。。我该怎么解决这个问题?在

screenshot of the csv file


Tags: nameimportoscontainerfilename字符requestsprice
1条回答
网友
1楼 · 发布于 2024-05-03 07:51:41

使用csv模块管理CSV文件,并使用utf-8-sigfor Excel正确识别UTF-8。打开文件时,请确保按照csv文档使用newline=''。在

示例:

import csv

filename = 'AM4.csv'
with open(filename,'w',newline='',encoding='utf-8-sig') as f:
    w = csv.writer(f)
    w.writerow(['Motherboard_Name','Price'])
    name = 'some name'
    price = '\u20b95,99'
    w.writerow([name,price.replace(',','')])

Excel image

相关问题 更多 >