【发布时间】:2017-09-24 00:06:23
【问题描述】:
我正在开发一个 python 网络爬虫来从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
【问题讨论】:
标签: python encoding web-scraping beautifulsoup lxml