Requests 代理池
Requests 本身不提供代理池,然而爬数据又要用,所以只能自己搞。其实还挺简单的。我也不知道为什么这么有用的 feature 一直没有被加入。
import requests
class Client:
def __init__(self):
self._session = requests.Session()
self.proxies = None
def set_proxy_pool(self, proxies, auth=None, https=True):
"""Randomly choose a proxy for every GET/POST request
:param proxies: list of proxies, like ["ip1:port1", "ip2:port2"]
:param auth: if proxy needs auth
:param https: default is True, pass False if you don't need https proxy
"""
from random import choice
if https:
self.proxies = [{'http': 'http://' + p, 'https': 'https://' + p} for p in proxies]
else:
self.proxies = [{'http': 'http://' + p} for p in proxies]
def get_with_random_proxy(url, **kwargs):
proxy = choice(self.proxies)
kwargs['proxies'] = proxy
if auth:
kwargs['auth'] = auth
return self._session.original_get(url, **kwargs)
def post_with_random_proxy(url, *args, **kwargs):
proxy = choice(self.proxies)
kwargs['proxies'] = proxy
if auth:
kwargs['auth'] = auth
return self._session.original_post(url, *args, **kwargs)
self._session.original_get = self._session.get
self._session.get = get_with_random_proxy
self._session.original_post = self._session.post
self._session.post = post_with_random_proxy
def remove_proxy_pool(self):
self.proxies = None
self._session.get = self._session.original_get
self._session.post = self._session.original_post
del self._session.original_get
del self._session.original_post
# You can define whatever operations using self._session
替换掉 Session 原本的 get 和 post 方法就行了,不会有什么副作用。class Client 并不必需,直接操作 Session 是一样的。
可以用 httpbin 来做验证
def test_proxy():
# visit http://cn-proxy.com/ to get available proxies if test failed
proxy_ips = ['112.25.41.136', '180.97.29.57']
client = Client()
client.set_proxy_pool(proxy_ips)
for _ in range(5):
result = client._session.get('http://httpbin.org/ip').json()
assert result['origin'] in proxy_ips
result = client._session.post('http://httpbin.org/post',
data={'m':'1'}).json()
assert result['form'] == {'m': '1'}
print(result['origin'])
assert result['origin'] in proxy_ips
client.remove_proxy_pool()
client.set_proxy_pool(proxy_ips, https=False)
for _ in range(5):
result = client._session.get('http://httpbin.org/ip').json()
print(result['origin'])
assert result['origin'] in proxy_ips
转载自 :https://laike9m.com/blog/requests-dai-li-chi,92/
Requests 代理池的更多相关文章
- requests ip代理池单ip和多ip设置方式
reqeusts库,在使用ip代理时,单ip代理和多ip代理的写法不同 (目前测试通过,如有错误,请评论指正) 单ip代理模式 省去headers等 import requests proxy = { ...
- python代理池的构建1——代理IP类的构建,以及配置文件、日志文件、requests请求头
一.整体结构 二.代理IP类的构建(domain.py文件) ''' 实现_ init_ 方法, 负责初始化,包含如下字段: ip: 代理的IP地址 port:代理IP的端口号 protocol: 代 ...
- 进程线程协程补充、docker-compose一键部署项目、搭建代理池、requests超时设置、认证设置、异常处理、上传文件
今日内容概要 补充:进程,线程,协程 docker-compose一键部署演示 搭建代理池 requests超时设置 requests认证设置 requests异常处理 requests上传文件 内容 ...
- Python爬虫代理池
爬虫代理IP池 在公司做分布式深网爬虫,搭建了一套稳定的代理池服务,为上千个爬虫提供有效的代理,保证各个爬虫拿到的都是对应网站有效的代理IP,从而保证爬虫快速稳定的运行,当然在公司做的东西不能开源出来 ...
- 开源IP代理池续——整体重构
开源IP代理池 继上一篇开源项目IPProxys的使用之后,大家在github,我的公众号和博客上提出了很多建议.经过两周时间的努力,基本完成了开源IP代理池IPProxyPool的重构任务,业余时间 ...
- Python实现的异步代理爬虫及代理池
使用python asyncio实现了一个异步代理池,根据规则爬取代理网站上的免费代理,在验证其有效后存入redis中,定期扩展代理的数量并检验池中代理的有效性,移除失效的代理.同时用aiohttp实 ...
- 爬取西刺ip代理池
好久没更新博客啦~,今天来更新一篇利用爬虫爬取西刺的代理池的小代码 先说下需求,我们都是用python写一段小代码去爬取自己所需要的信息,这是可取的,但是,有一些网站呢,对我们的网络爬虫做了一些限制, ...
- scrapy_随机ip代理池
什么是ip代理? 我们电脑访问网站,其实是访问远程的服务器,通过ip地址识别是那个机器访问了服务器,服务器就知道数据该返回给哪台机器,我们生活中所用的网络是局域网,ip是运营商随机分配的,是一种直接访 ...
- 使用redis所维护的代理池抓取微信文章
搜狗搜索可以直接搜索微信文章,本次就是利用搜狗搜搜出微信文章,获得详细的文章url来得到文章的信息.并把我们感兴趣的内容存入到mongodb中. 因为搜狗搜索微信文章的反爬虫比较强,经常封IP,所以要 ...
随机推荐
- JS基础_打印99乘法表
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 编译程序遇到问题 relocation R_X86_64_32 against `.rodata' can not be used when making a shared object;
编译程序遇到问题 relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; 发现编译 ...
- winfrom---Window 消息大全
最近正在捣腾winfrom,遇到了关于window消息这一块的东西,正好在网上看到“微wx笑”的总结. 原文地址:http://blog.csdn.net/testcs_dn/article/deta ...
- django orm 数据查询详解
一 在django里面创建模型 from django.db import models class Blog(models.Model): name = models.CharField(max_l ...
- 深入学习Mybatis框架(二)- 进阶
1.动态SQL 1.1 什么是动态SQL? 动态SQL就是通过传入的参数不一样,可以组成不同结构的SQL语句. 这种可以根据参数的条件而改变SQL结构的SQL语句,我们称为动态SQL语句.使用动态SQ ...
- 使用busybox1.21.1制作根文件系统
1. 下载源码 https://busybox.net/downloads/ 2. 解压 3. 修改Makefile ~/busybox-1.21.1$ vi Makefile 164行: 修改前:C ...
- zencart清空产品商品实用命令
TRUNCATE TABLE categories; TRUNCATE TABLE categories_description;TRUNCATE TABLE meta_tags_categories ...
- Hdu 1525 欧几里得博弈
两堆石子每次可以在大堆中取小堆的倍数个石子 第一个拿光某个堆的玩家赢 假设a>=b 必胜状态:a%b==0或a/b>=2 因为当a/b>=2时 当前玩家可以选择将状态转移至 a%b+ ...
- Codeforces 1082 毛毛虫图构造&最大权闭合子图
A #include<bits/stdc++.h> using namespace std; typedef long long ll; , MAXM = ; //int to[MAXM ...
- socket 测试工具java
SocketTest.jar http://sockettest.sourceforge.net/