当使用urllib.request.urlopen打开包含中文的链接时报错:
from urllib import request
url = 'https://baike.baidu.com/item/糖尿病'
response = request.urlopen(url)
提示错误:UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 10-12: ordinal not in range(128)
参考https://www.zhihu.com/question/22899135得知,
urllib.request.urlopen不支持中英文混合的字符串。
应使用urllib.parse.quote进行转换。
#coding=utf-8
from urllib import request
from urllib.parse import quote
import string
url = 'https://baike.baidu.com/item/糖尿病'
s = quote(url,safe=string.printable)
response = request.urlopen(s)
运行正确。
方法quote的参数safe表示可以忽略的字符。
string.printable表示ASCII码第33~126号可打印字符,其中第48~57号为0~9十个阿拉伯数字;65~90号为26个大写英文字母,97~122号为26个小写英文字母,其余的是一些标点符号、运算符号等。
如果不设置这个safe参数,’https://baike.baidu.com/item/糖尿病’会被转换为
‘https%3A//baike.baidu.com/item/%E7%B3%96%E5%B0%BF%E7%97%85’,
而不是’https://baike.baidu.com/item/%E7%B3%96%E5%B0%BF%E7%97%85’