python如何用IP代理

  • 时间:
  • 来源:网络

   

python用IP代理的方法:首先创建代理ip对象;然后定制一个opener对象;接着urlopen就一直使用这个代理地址;最后发出请求时,就是用到这个代理地址了。

【相关学习推荐:python教程】

python用IP代理的方法:

python使用代理的方法有两种

1.

 1 #先创建代理ip对象
 2 proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})
 3 
 4 #定制一个opener对象
 5 opener = urllib.request.build_opener(proxy_support)
 6 
 7 #安装这个opener对象,以后的urlopen就一直使用这个代理地址了
 8 urllib.request.install_opener(opener)
 9 
10 #发出请求时,就是用到这个代理地址了
11 html = urllib.request.urlopen('xxxxxxxxxx').read()

2.

1 #先创建代理ip对象
2 proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})
3 
4 #定制一个opener对象
5 opener = urllib.request.build_opener(proxy_support)
6 
7 #这里可以直接使用opener对象发出请求
8 html = opener.open('xxxxxxxxx').read()

示例代码:

 1 import urllib.request
 2 
 3 #这一段三句话是为了请求时带上浏览器标识,因为有的网站看到是爬虫的标识直接返回403
 4 #请求的网站不涉及到提交数据,所以没有给出data参数
 5 url = 'https://whatismyipaddress.com/'
 6 header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
 7 req = urllib.request.Request(url,headers=header)
 8 
 9 #使用代理和还原不使用代理的方法
10 #if语句相当于一个开关,不要写成True
11 use_proxy = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})
12 null_proxy = urllib.request.ProxyHandler()
13 if True:
14     opener = urllib.request.build_opener(use_proxy)
15 else:
16     opener = urllib.request.build_opener(null_proxy)
17 #根据上面的开关,安装的opener对象是否带有代理地址
18 urllib.request.install_opener(opener)
19 
20 #获取返回结果
21 #同时可以使用html = opener.open(req).read()获取结果
22 html = urllib.request.urlopen(req).read()
23 
24 #这网页返回页面的内容太多,在控制台不好查看,
25 #并且返回的内容是二进制格式,可以直接写入文件,当个网页查看
26 with open('E:\\\\whatismyip.html','wb') as file:
27     file.write(html)
28     print('OK')

想了解更多相关学习,敬请关注php培训栏目!