【问题标题】:problem of urlretrieve cannot get image from url contains unicode stringurlretrieve 的问题无法从 url 获取包含 unicode 字符串的图像
【发布时间】:2019-12-07 15:37:29
【问题描述】:

我编写了一个 python 脚本来从 url 中检索图像:

url = `https://uploads0.wikiart.org/images/albrecht-durer/watermill-at-the-montaсa.jpg`
urllib.request.urlretrieve(url, STYLE_IMAGE_UPLOAD + "wikiart" + "/" + url)

当我跑步时,我收到了消息

UnicodeEncodeError: 'ascii' codec can't encode character '\u0441' in position 49: ordinal not in range(128)

我认为是图片网址的问题

'https://uploads0.wikiart.org/images/albrecht-durer/watermill-at-the-monta\u0441a.jpg',

如何解决这个问题?

【问题讨论】:

  • 你能发布完整的堆栈跟踪吗?此外,您的代码 sn-p 不可重现,因为我们不知道 STYLE_IMAGE_UPLOAD 是什么。
  • 哦,我明白了,“Montaca”中的“c”是一个西里尔字母。您是否尝试过对地址进行 url 编码?
  • 顺便说一句,here 是更通用的方法和替代解决方案的集合。例如,我了解到requests 库可以开箱即用地处理类似的地址。

标签: python python-3.x unicode python-unicode


【解决方案1】:

URL 包含一个非 ASCII 字符(一个西里尔字母,看起来像拉丁语“c”)。

使用urllib.parse.quote 函数转义该字符:

url = 'https://uploads0.wikiart.org' + urllib.parse.quote('/images/albrecht-durer/watermill-at-the-montaсa.jpg')
urllib.request.urlretrieve(url, '/tmp/watermill.jpg')

不要将整个 URL 放在 quote 函数中,否则会转义 "https://" 中的冒号 (":")。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2012-02-20
    相关资源
    最近更新 更多