url检索问题无法从包含unicode字符串的url获取图像

2024-09-26 18:15:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个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)

我认为问题出在图片的url上

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

如何解决这个问题


Tags: theinhttpsorg脚本urlatjpg
1条回答
网友
1楼 · 发布于 2024-09-26 18:15:47

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://”中转义冒号(“:”)

相关问题 更多 >

    热门问题