URL 国家字符给出 UnicodeEncodeError

URL with national characters giving UnicodeEncodeError

我正在尝试提取字典条目:

url = 'http://www.lingvo.ua/uk/Interpret/uk-ru/вікно'
# parsed_url = urlparse(url)
# parameters = parse_qs(parsed_url.query)
# url = parsed_url._replace(query=urlencode(parameters, doseq=True)).geturl()
page = urllib.request.urlopen(url)
pageWritten = page.read()
pageReady = pageWritten.decode('utf-8')
xmldata = lxml.html.document_fromstring(pageReady)
text = xmldata.xpath(//div[@class="js-article-html g-card"])

无论是打开还是关闭注释行,它都会不断出现错误:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 24-28: ordinal not in range(128)

您的问题是您的 URL 路径中有非 ASCII 字符,必须使用 Python 中的 urllib.parse.quote(string) in Python 3 or urllib.quote(string) 正确编码 2.

# Python 3
import urllib.parse
url = 'http://www.lingvo.ua' + urllib.parse.quote('/uk/Interpret/uk-ru/вікно')

# Python 2
import urllib
url = 'http://www.lingvo.ua' + urllib.quote(u'/uk/Interpret/uk-ru/вікно'.encode('UTF-8'))

注意:根据 What is the proper way to URL encode Unicode characters?,URLs 应编码为 UTF-8。但是,这并不排除对生成的非 ASCII、UTF-8 字符进行百分比编码。