我用python编写了一个脚本,使用post请求从网页中提取json内容。当我运行脚本时,我在控制台中得到了预期的结果。但是,当我尝试在csv文件中写入相同的内容时,我遇到了一个问题。
当我试着说:
with open ("outputContent.csv","w",newline="") as f:
我遇到以下错误:
Traceback (most recent call last):
File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\all_reviews_grabber.py", line 27, in <module>
writer.writerow([nom,ville,region])
File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\ufb02' in position 16: character maps to <undefined>
当我尝试以下操作时,脚本会生成一个充满数据的csv文件:
with open ("outputContent.csv","w",newline="",encoding="utf-8") as f:
但是,csv文件包含一些难以辨认的内容,如:
Beijingshì
Xinjiangwéiwúerzìzhìqu
Shà nghaishì
Qingpuqu
Shà nghaishì
Xúhuìqu
Putuóqu
这是我目前的剧本:
import csv
import requests
from bs4 import BeautifulSoup
baseUrl = "https://fr-vigneron.gilbertgaillard.com/importer"
postUrl = "https://fr-vigneron.gilbertgaillard.com/importer/ajax"
with requests.Session() as s:
req = s.get(baseUrl)
sauce = BeautifulSoup(req.text,"lxml")
token = sauce.select_one("input[name='_token']")['value']
payload = {
'data': 'country=0&type=0&input_search=',
'_token': token
}
res = s.post(postUrl,data=payload)
with open ("outputContent.csv","w",newline="",encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(['nom','ville','region'])
for item in res.json():
nom = item['prospect_nom']
ville = item['prospect_ville']
region = item['prospect_region']
print(nom,ville,region)
writer.writerow([nom,ville,region])
如何以正确的方式将内容写入csv文件?
看看这个-http://www.pgbovine.net/unicode-python-errors.htm
检查解释器中的默认编码:
导入系统
你知道吗系统标准编码
Python的旧版本也可能导致此错误。
使用pandas进行解析和编写会缓解这个问题吗?你知道吗
只要删除
print
语句,代码就可以正常工作。你知道吗您看到的损坏数据是因为您正在解码来自cp1252的文件数据,而不是在查看UTF-8时。你知道吗
如果您是通过在Python中打开csv文件来查看数据,请确保在打开它时指定UTF-8编码:
如果使用Excel等应用程序打开文件,请确保在打开文件时指定编码为UTF-8。你知道吗
如果您没有指定编码,那么默认的cp1252编码将用于解码文件中的数据,您将看到垃圾数据。你知道吗
*
print
将自动使用默认编码,因此如果它尝试对无法编码为cp1252的字符进行编码,则会出现异常。你知道吗相关问题 更多 >
编程相关推荐