python3中的urlopen对于中文url的处理 不指定

jed , 2017-6-22 14:24 , Python学习 , 评论(0) , 阅读(61334) , Via 本站原创 | |
urllib.request.urlopen('http://www.sina.com.cn'),如果url中有中文怎么办,Python3不是默认采用utf-8编码的吗?但是还是出现了如下错误

UnicodeEncodeError: 'ascii' codec can't encode characters in position 78-89: ordinal not in range(128)

主要是由于url中带有中文导致的。

刚刚看了urllib.parse.quote()的定义,完全可以直接处理中英混排的url,无需单独处理中文再拼接。具体方法:

# -*- 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 = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","

这样对于爬取来的混合中文的url可以直接处理了。
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]