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可以直接处理了。
<?php
$requestUrl = 'ip138.com';
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $requestUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); //代理认证模式
curl_setopt($ch, CURLOPT_PROXY, "112.65.219.72"); //代理服务器地址
curl_setopt($ch, CURLOPT_PROXYPORT, 80); //代理服务器端口
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, ":"); //http代理认证帐号,username:password的格式
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); //使用http代理模式
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;
?>
此段代码是使用了curl实现了网页代理的功能,这是curl类库内置的代理功能,不做过多解释,需要提醒的是,curl类库一般需要自己更改php.ini才能实现的