首页 > 解决方案 > Python 编码 '\xdf' / '\xc3\x9f' 到 'ß'

问题描述

我正在下载一个网站的 html 并用这样的漂亮汤美化它:

f_page_soup = Soup(f_driver.page_source, "lxml")
with open(f_filename_pretty, 'wb') as f_output:
    f_output.write(f_page_soup.prettify(encoding='utf-8'))

并像这样打开美化的html:

ecjData = open(filename, 'r', encoding='utf-8').read()
    pageSoup = Soup(ecjData, "lxml")

html 内部是我想用 BeautifulSoup 收集的不同链接。其中一个看起来像这样example.com/weiß/3

遍历所有链接后,我想打印它们。这样做:

print ("https://example.com" + a["href"])

UnicodeEncodeError正如预期的那样,给了我上面的链接。

因此,在发现错误后,我尝试对其进行解码:

print (("https://example.com" + a["href"]).encode('utf-8').decode('latin-1'))

这导致

'ascii' codec can't encode characters in position 78-79: ordinal not in range(128)

我尝试的另一种方法是在字符串内部替换:

print (str(("https://example.com" + a["href"]).encode('utf-8')).replace('\\xc3\\x9f','ß'))

然后再次导致:

'ascii' codec can't encode character '\xdf' in position 80: ordinal not in range(128)

基本上我需要打印的是:

"https://example.com/weiß/3"

我怎样才能做到这一点?我正在使用python 3.5。

标签: pythonencodingbeautifulsoup

解决方案


推荐阅读