Python:打开带重音的 URL [英] Python: open a URL with accent

查看:27
本文介绍了Python:打开带重音的 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 2.7 中,我想打开一个包含重音符号的 URL(链接本身,而不是它指向的页面).如果我使用以下内容:

#!/usr/bin/env Python# -*- 编码:utf-8 -*-导入 urllib2测试 = "https://www.notifymydevice.com/push?ApiKey=K6HGFJJCCQE04G29OHSRBIXI&PushTitle=Les%20accents%20:%20éèçà&PushText=Messages%20éèçà&"urllib2.urlopen(测试)

我的口音被转换为胡言乱语(Ã、¨、© 等,而不是我期望的 éèà).

我已经搜索过这种问题,所以我尝试了 urllib2.urlopen(test.encode('utf-8')) 但在这种情况下 Python 会抛出一个错误:><块引用>

文件test.py",第 10 行,在urllib2.urlopen(test.encode('utf8')) UnicodeDecodeError: 'ascii' 编解码器无法解码第 98 位的字节 0xc3:序号不在范围内 (128)

解决方案

u 前缀字符串.使用这个在 repl 中尝试它没有错误

导入urllibtest = u'https://www.notifymydevice.com/push?ApiKey=K6HGFJJCCQE04G29OHSRBIXI&PushTitle=Les%20accents%20:%20éèçà&PushText=Messages%20éèçà&'urllib.urlopen(test.encode("UTF-8"))

u 前缀用于 unicode字符串

In Python 2.7, I want to open a URL which contains accents (the link itself, not the page to which it's pointing). If I use the following:

#!/usr/bin/env Python
# -*- coding: utf-8 -*-

import urllib2


test = "https://www.notifymydevice.com/push?ApiKey=K6HGFJJCCQE04G29OHSRBIXI&PushTitle=Les%20accents%20:%20éèçà&PushText=Messages%20éèçà&"

urllib2.urlopen(test)

My accents are converted to gibberish (Ã, ¨, ©, etc rather than the éèà I expect).

I've searched for that kind of issue and so I tried with urllib2.urlopen(test.encode('utf-8')) but Python throws an error in that case:

File "test.py", line 10, in urllib2.urlopen(test.encode('utf8')) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 98: ordinal not in range(128)

解决方案

Prefix the string with a u. I get no errors trying it out in repl using this

import urllib
test = u'https://www.notifymydevice.com/push?ApiKey=K6HGFJJCCQE04G29OHSRBIXI&PushTitle=Les%20accents%20:%20éèçà&PushText=Messages%20éèçà&'
urllib.urlopen(test.encode("UTF-8"))

The u prefix is for unicode strings

这篇关于Python:打开带重音的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆