我正在使用python web scraper從this webpage中提取數據。它包含像ą,č,è,ė,į,š,ø,ū,ž這樣的拉丁字符。我使用BeautifulSoup來識別編碼:拉丁文編碼問題
def decode_html(html_string):
converted = UnicodeDammit(html_string)
print(converted.original_encoding)
if not converted.unicode_markup:
raise UnicodeDecodeError(
"Failed to detect encoding, tried [%s]",
', '.join(converted.tried_encodings))
return converted.unicode_markup
它似乎總是使用的編碼是「windows-1252」。但是,當打印到文件或控制檯時,這會將字符如?變成ë和ø。我使用lxml庫來刮取數據。所以我認爲它使用了錯誤的編碼,但奇怪的是,如果我使用lxml.html.open_in_browser(decoded_html)
,所有字符都恢復正常。如何在沒有所有mojibake的情況下將文字打印到文件中?
這是我在用的輸出:
def write(filename, obj):
with open(filename, "w", encoding="utf-8") as output:
json.dump(obj, output, cls=CustomEncoder, ensure_ascii=False)
return
這是不是有一個不同的潛在問題,它會始終用字符集標題中提供的編碼重寫文檔中指定的編碼? – pvg
@pvg:是的,如果服務器明確設置了編碼*和* HTML文檔設置了一個(通過meta標頭),那麼在這種情況下,服務器內容類型會勝出。我將用一個首先查找HTML聲明的解決方案進行更新。 –