当前第2页 返回上一页
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import urllib2
import random
proxy_list = [
{ "http" : "124.88.67.81:80" },
{ "http" : "124.88.67.81:80" },
{ "http" : "124.88.67.81:80" },
{ "http" : "124.88.67.81:80" },
{ "http" : "124.88.67.81:80" }
]
# 随机选择一个代理
proxy = random.choice(proxy_list)
# 使用选择的代理构建代理处理器对象
httpproxy_handler = urllib2.ProxyHandler(proxy)
opener = urllib2.build_opener(httpproxy_handler)
request = urllib2.Request( "http://www.baidu.com/" )
response = opener.open(request)
print response.read()
|
上面使用的都是免费代理,不是很稳定,很多时候会出现无法使用的情况,这时候可以考虑使用私密代理。也就是向代理供应商购买代理,供应商会提供一个有效代理,并且有自己的用户名和密码,具体使用和免费代理一样,这是多了一个账户认证,如下:
1 2 | # 构建具有一个私密代理IP的Handler,其中user为账户,passwd为密码
httpproxy_handler = urllib2.ProxyHandler({ "http" : "user:passwd@124.88.67.81:80" })
|
上面就是使用urllib2设置代理的方法,不过看起来有些麻烦,下面我们看看如何使用reqursts来使用代理。
使用免费代理:
1 2 3 4 5 | import requests
# 如果代理需要使用HTTP Basic Auth,可以使用下面这种格式:
proxy = { "http" : "mr_mao_hacker:sffqry9r@61.158.163.130:16816" }
response = requests.get( "http://www.baidu.com" , proxies = proxy)
print response.text
|
注:可以将账户密码写入环境变量以免泄露
以上就是Python爬虫如何设置代理的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
Python中如何搭建虚拟环境?Python搭建虚拟环境的步骤
Python如何判断闰年
Python主要做什么开发
Python中常用列表方法分享
Python卸载不了怎么办
什么是Python re.match函数?(实例解析)
Python注释怎么写
Python怎样实现百度语音识别api的步奏详解
Python32位和64位有什么区别
Python web开发用什么工具
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python爬虫如何设置代理