>  기사  >  백엔드 개발  >  Python 프록시 IP를 작성하는 방법

Python 프록시 IP를 작성하는 방법

coldplay.xixi
coldplay.xixi원래의
2020-10-28 10:22:0112275검색

python写代理ip的方法:首先创建代理ip对象,并定制一个opener对象;然后安装opener对象,以后的urlopen就一直使用这个代理地址。

Python 프록시 IP를 작성하는 방법

python写代理ip的方法:

方法1:

先创建代理ip对象

proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})

定制一个opener对象

opener = urllib.request.build_opener(proxy_support)

安装这个opener对象,以后的urlopen就一直使用这个代理地址了

urllib.request.install_opener(opener)

发出请求时,就是用到这个代理地址了

html = urllib.request.urlopen('xxxxxxxxxx').read()

方法2:

先创建代理ip对象

proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})

定制一个opener对象

opener = urllib.request.build_opener(proxy_support)

这里可以直接使用opener对象发出请求

html = opener.open('xxxxxxxxx').read()

示例代码:

import urllib.request
#这一段三句话是为了请求时带上浏览器标识,因为有的网站看到是爬虫的标识直接返回403
#请求的网站不涉及到提交数据,所以没有给出data参数
url = 'https://whatismyipaddress.com/'
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'}
req = urllib.request.Request(url,headers=header)
#使用代理和还原不使用代理的方法
#if语句相当于一个开关,不要写成True
use_proxy = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})
null_proxy = urllib.request.ProxyHandler()
if True:
    opener = urllib.request.build_opener(use_proxy)
else:
    opener = urllib.request.build_opener(null_proxy)
#根据上面的开关,安装的opener对象是否带有代理地址
urllib.request.install_opener(opener)
#获取返回结果
#同时可以使用html = opener.open(req).read()获取结果
html = urllib.request.urlopen(req).read()
#这网页返回页面的内容太多,在控制台不好查看,
#并且返回的内容是二进制格式,可以直接写入文件,当个网页查看
with open('E:\\whatismyip.html','wb') as file:
    file.write(html)
    print('OK')

相关免费学习推荐:python教程(视频)

위 내용은 Python 프록시 IP를 작성하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.