代理参数-proxies
-
定义及分类
【1】定义 : 代替你原来的IP地址去对接网络的IP地址 【2】作用 : 隐藏自身真实IP,避免被封
-
普通代理
【1】获取代理IP网站 快代理、全网代理、代理精灵、... ... 【2】参数类型 proxies = { '协议':'协议://IP:端口号' } proxies = { 'http':'http://IP:端口号', 'https':'https://IP:端口号', }
-
普通代理 - 示例
# 使用免费普通代理IP访问测试网站: http://httpbin.org/get import requests url = 'http://httpbin.org/get' headers = {'User-Agent':'Mozilla/5.0'} # 定义代理,在代理IP网站中查找免费代理IP proxies = { 'http':'http://112.85.164.220:9999', 'https':'https://112.85.164.220:9999' } html = requests.get(url,proxies=proxies,headers=headers,timeout=5).text print(html)
-
私密代理+独享代理
【1】语法结构 proxies = { '协议':'协议://用户名:密码@IP:端口号' } 【2】示例 proxies = { 'http':'http://用户名:密码@IP:端口号', 'https':'https://用户名:密码@IP:端口号', }
-
私密代理+独享代理 - 示例代码
import requests url = 'http://httpbin.org/get' proxies = { 'http': 'http://309435365:szayclhp@106.75.71.140:16816', 'https':'https://309435365:szayclhp@106.75.71.140:16816', } headers = { 'User-Agent' : 'Mozilla/5.0', } html = requests.get(url,proxies=proxies,headers=headers,timeout=5).text print(html)
-
建立自己的代理IP池 - 开放代理 | 私密代理
""" 收费代理: 建立开放代理的代理IP池 思路: 1、获取到开放代理 2、依次对每个代理IP进行测试,能用的保存到文件中 """ import requests class ProxyPool: def __init__(self): self.url = '代理网站的API链接' self.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'} # 打开文件,用来存放可用的代理IP self.f = open('proxy.txt', 'w') def get_html(self): html = requests.get(url=self.url, headers=self.headers).text proxy_list = html.split('\r\n') for proxy in proxy_list: # 依次测试每个代理IP是否可用 if self.check_proxy(proxy): self.f.write(proxy + '\n') def check_proxy(self, proxy): """测试1个代理IP是否可用,可用返回True,否则返回False""" test_url = 'http://httpbin.org/get' proxies = { 'http' : 'http://{}'.format(proxy), 'https': 'https://{}'.format(proxy) } try: res = requests.get(url=test_url, proxies=proxies, headers=self.headers, timeout=2) if res.status_code == 200: print(proxy,'\033[31m可用\033[0m') return True else: print(proxy,'无效') return False except: print(proxy,'无效') return False def run(self): self.get_html() # 关闭文件 self.f.close() if __name__ == '__main__': spider = ProxyPool() spider.run()