Python3 urllib.request读取带中文的链接

两种方法,一种是将中文单独拿出进行处理,然后进行字符串拼接;另一种是直接对链接进行修改。

第一种方法,将中文单独拿出

# -*- coding:utf-8 -*-

from urllib.parse import quote

url = 'http://www.example.com/api.php?text=中文在这里'

x = '中文在这里'
x = quote(x)
print(x)
y = 'http://www.example.com/api.php?text='
print(y + x)

运行结果如下

%E4%B8%AD%E6%96%87%E5%9C%A8%E8%BF%99%E9%87%8C
http://www.example.com/api.php?text=%E4%B8%AD%E6%96%87%E5%9C%A8%E8%BF%99%E9%87%8C

第二种方法,直接对链接进行处理

# -*- coding:utf-8 -*-

from urllib.parse import quote


url = 'http://www.example.com/api.php?text=中文在这里'

# 不带附加参数
print('\n不带附加参数:\n%s' % quote(url))

# 附带不转换字符参数
print('\n附加不转换字符参数:\n%s' % quote(url, safe='/:?=&'))

运行结果如下

不带附加参数:
http%3A//www.example.com/api.php%3Ftext%3D%E4%B8%AD%E6%96%87%E5%9C%A8%E8%BF%99%E9%87%8C

附加不转换字符参数:
http://www.example.com/api.php?text=%E4%B8%AD%E6%96%87%E5%9C%A8%E8%BF%99%E9%87%8C

quote可用的参数如下:

quote(string, safe='/', encoding=None, errors=None)

其中safe参数可用的范围

reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
参考网站:https://www.zhihu.com/question/22899135

猜你喜欢

转载自blog.csdn.net/caorya/article/details/80292221