python3 urlopen打开包含中文的url

  今天在写一个爬虫的时候,抓取的页面url地址后,解析不了,然后百度查了下,地址里面的中文要转换掉

from urllib import request
from urllib.parse import quote
import string
class HtmlDownload(object):
    def download(self, new_url):
        if new_url is None:
            return
        s = quote(new_url,safe=string.printable)    #用quote转换
        resp = request.urlopen(s)
        if resp.status != 200:
            return
        return resp.read().decode('utf-8')

  

方法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

上面的是网上找来的

posted @ 2018-07-05 17:31  tengjian  阅读(586)  评论(0编辑  收藏  举报