urllib2.urlopen()函数不支持验证、cookie或者其它HTTP高级功能。要支持这些功能,必须使用build_opener()函数创建自定义Opener对象。
1. build_opener([handler1 [ handler2, ... ]])
参数handler是Handler实例,常用的有HTTPBasicAuthHandler、HTTPCookieProcessor、ProxyHandler等。
build_opener ()返回的对象具有open()方法,与urlopen()函数的功能相同。
1. build_opener([handler1 [ handler2, ... ]])
参数handler是Handler实例,常用的有HTTPBasicAuthHandler、HTTPCookieProcessor、ProxyHandler等。
build_opener ()返回的对象具有open()方法,与urlopen()函数的功能相同。
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可以直接处理了。
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可以直接处理了。