python - 无法将从 XPath 抓取的德语字符写入 CSV 文件
问题描述
我正在尝试将包含德语变音符号的信息写入 CSV。当我只写第一个参数“名称”时,它会正确显示。如果我写“名称”和“机构”,我会收到这个错误:
UnicodeEncodeError: 'charmap' codec can't encode character '\u0308' in position 71: character maps to <undefined>
正如您在下面的代码中看到的,我尝试使用不同的字符组合对文本进行编码和解码。
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
# this is the header of the csv
with open('/filepath/result.csv', 'w', encoding='utf-8') as f:
f.write("name, institution, \n")
l = list(range(1148, 1153))
for i in l:
url = 'webaddress.com' + str(i)
driver.get(url)
name = driver.find_elements_by_xpath('//div[@style="width:600px; display:inline-block;"]')[0].text
name = '\"' + name + '\"'
institution = driver.find_elements_by_xpath('//div[@style="width:600px; display:inline-block;"]')[1].text
institution = '\"' + institution + '\"'
print(str(i) + ': ' + name, '\n', str(i) + ': ' + institution, '\n')
print(institution.encode('utf-8'))
print(institution.encode('utf-8').decode('utf-8'))
print(institution.encode('utf-8').decode('ISO-8859-15'))
with open('/filepath/result.csv', 'a', encoding='utf-8') as f:
f.write(name + ',' + institution + '\n')
driver.close()
当我将所有编码设置为 UTF-8 时,CSV 中显示的结果看起来就像我对 UTF-8 进行编码并解码 ISO-8859-15 (latin1) 的结果。当我编码 latin1 并解码 utf-8 时,我得到了与上面相同的错误。
谢谢您的帮助。
解决方案
您似乎对encode
. 你为什么要print(institution.encode('utf-8').decode('utf-8'))
;这简直等同于print(institution)
!
我猜你的回溯来自print
s 而不是write()
. 尝试取出有问题的人;或者简单地弄清楚如何将 Unicode 打印到您的控制台,然后就这样做。
可能读过 Ned Batchelder 的Pragmatic Unicode。
推荐阅读
- python-3.x - python字符串是否包含引号?
- excel - Octave:无法将可选参数传递给 VBA 函数(通过 COM 服务器添加 excel 表时)
- android - Android Volley Request 完全失败
- c# - Discord 在我的 GitHub 上编译的 dll 中找到了机器人令牌
- android - Gradle 卡住了项目的同步
- python - 数据框形状问题
- c++ - 如何获取传递给可变参数模板函数的每个容器的元素类型
- python - 最小数函数
- c++ - 向 Win32 ListView 添加填充
- bash - 在 Bash 脚本中使用循环在数组上分配变量