【问题标题】:URL with national characters giving UnicodeEncodeError带有给出 UnicodeEncodeError 的国家字符的 URL
【发布时间】:2015-05-15 13:40:50
【问题描述】:

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

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)

【问题讨论】:

  • 我怀疑这是否来自注释行:它几乎肯定来自decode('utf-8') 调用,如果您发布了回溯就很清楚了。为什么需要那条线?如果删除它会发生什么?
  • @DanielRoseman 没有任何变化,同样的错误。我在这里stackoverflow.com/questions/29435893/… 遇到了同样的问题,但现在我使用不同的 url 没有参数(这就是我评论这些行的原因)。还是不知道答案
  • @MartinPieters 我可以请你帮忙吗?你已经在这里帮助过一次stackoverflow.com/questions/29435893/…
  • @cpburnz 没有成功(
  • 您应该养成在问题中包含完整回溯的习惯。到目前为止,我认为问题出在您的.decode 上。问题是网址...

标签: python character-encoding


【解决方案1】:

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

# 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?,URL 应编码为 UTF-8。但是,这并不排除对生成的非 ASCII、UTF-8 字符进行百分比编码。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 2014-01-12
  • 2010-12-02
  • 1970-01-01
  • 2015-07-10
  • 2015-12-26
  • 1970-01-01
相关资源
最近更新 更多