簡體   English   中英

如何修復UnicodeEncodeError :?

[英]how to fix UnicodeEncodeError:?

因此,我正嘗試從本地網站上刪除有關主板的數據。

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':字符映射到

我怎樣才能解決這個問題??

編輯::因此我通過添加encoding =“ utf-8”(如此處提到的python 3.2 UnicodeEncodeError:'charmap'編解碼器無法對位置9629的字符'\\ u2013'進行編碼來解決unicode錯誤:字符映射為<undefined > )(open(filename,'w',encoding =“ utf-8”)),它似乎可以完成工作,但是在csv文件中卻在價格之前獲得了像(¹)這樣的字符。我該如何解決這個?

csv文件的屏幕截圖

使用csv模塊管理CSV文件,並使用utf-8-sig for 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圖片

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM