您的位置:首页技术文章
文章详情页

python爬虫利用代理池更换IP的方法步骤

【字号: 日期:2022-06-27 13:34:41浏览:15作者:猪猪
0. 前言

周日在爬一个国外网站的时候,发现用协程并发请求,并且请求次数太快的时候,会出现对方把我的服务器IP封掉的情况。于是网上找了一下开源的python代理池,这里选择的是star数比较多的proxy_pool

1. 安装环境

# 安装python虚拟环境, python环境最好为python3.6,再往上的话,安装依赖时会报错sudo apt updatesudo apt install python3.6pip3 install virtualenvvirtualenv venv --python=python3.6source venv/bin/activate# 安装redissudo apt install redis-server# 启动redis serverredis-server 2. 安装依赖

git clone https://github.com/jhao104/proxy_pool.gitcd proxy_poolpip install -r requirements.txt3. 修改配置文件

# 修改setting.py # 配置API服务HOST = '0.0.0.0' # IPPORT = 5010 # 监听端口# 配置数据库# 以下为三个示例,根据redis的配置,选择其中一种即可# 一般启动redis时如果没有配置文件,那么选择第一种即可# 1. Redis IP: 127.0.0.1 Port: 6379DB_CONN = ’redis://@127.0.0.1:6379’# 2. Redis IP: 127.0.0.1 Port: 6379 Password: 123456DB_CONN = ’redis://:123456@127.0.0.1:6379’# 3. Redis IP: 127.0.0.1 Port: 6379 Password: 123456 DB: 15DB_CONN = ’redis://:123456@127.0.0.1:6379/15’ # 配置 ProxyFetcherPROXY_FETCHER = [ 'freeProxy01', # 这里是启用的代理抓取方法名,所有fetch方法位于fetcher/proxyFetcher.py 'freeProxy02', # ....]4. 启动

# 可以用tmux开三个窗口# 启动调度程序python proxyPool.py schedule# 启动webApi服务python proxyPool.py server5. 测试

import requestsdef get_proxy(): return requests.get('http://127.0.0.1:5010/get/').json()def delete_proxy(proxy): requests.get('http://127.0.0.1:5010/delete/?proxy={}'.format(proxy))# your spider codedef getHtml(): # .... retry_count = 5 proxy = get_proxy().get('proxy') while retry_count > 0: try: html = requests.get(’http://www.example.com’, proxies={'http': 'http://{}'.format(proxy)}) # 使用代理访问 return html except Exception: retry_count -= 1 # 删除代理池中代理 delete_proxy(proxy) return None

python爬虫利用代理池更换IP的方法步骤

更多的用法和文档请参考:document 和 https://github.com/jhao104/proxy_pool

到此这篇关于python爬虫利用代理池更换IP的方法步骤的文章就介绍到这了,更多相关python 代理池更换IP内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: Python 编程
相关文章: