簡體   English   中英

無法將從 XPath 抓取的德語字符寫入 CSV 文件

[英]Cannot write German characters scraped from XPath to CSV file

我正在嘗試將包含德語變音字符的信息寫入 CSV。 當我只寫第一個參數“name”時,它會正確顯示。 如果我寫“名稱”和“機構”,我會收到這個錯誤:

UnicodeEncodeError: 'charmap' codec can't encode character '\̈' 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 時,我遇到了與上面相同的錯誤。

感謝您的幫助。

foo.py文件頂部添加以下行:

# -*- coding: UTF-8 -*-

作為替代方案,您可以使用io模塊,如下所示:

import io

# this is the header of the csv
with io.open('/filepath/result.csv', 'w', encoding='utf-8') as f:
  f.write("name, institution, \n")

然后:

with io.open('/filepath/result.csv', 'a', encoding='utf-8') as f:
    f.write((name + ',' + institution + '\n')..encode("utf-8"))

您似乎對encode的目的感到困惑。 為什么要print(institution.encode('utf-8').decode('utf-8')) ; 這只是等價於print(institution)

我猜你的回溯來自print s之一,而不是write() 嘗試取出違規者; 或者只是弄清楚如何將 Unicode 打印到您的控制台,然后就這樣做。

可能閱讀 Ned Batchelder 的Pragmatic Unicode。

暫無
暫無

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

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