爬虫ip池

项目地址

下载项目

  • git clone
1
git clone git@github.com:jhao104/proxy_pool.git
  • 安装依赖(requirements.txt里面的依赖版本存在问题,需要修改)
    • 若出现报错:ImportError: cannot import name ‘json’from ‘itsdangerous’
      • pip install flask==2.0.2
    • 若出现报错:cannot import name ‘Markup’ from ‘jinja2’
      • pip uninstall jinja2
      • pip install jinja2==2.11.3
    • 若出现报错:ImportError: cannot import name ‘soft_unicode’ from ‘markupsafe’
      • pip uninstall markupsafe
      • pip install markupsafe==2.0.1
1
pip install -r requirements.txt

安装redis数据库

选择Redis-x64-5.0.14.1.zip

[Redis-x64-5.0.14.1.zip](Releases · tporadowski/redis (github.com))

  1. 解压后找到三个文件

    1. redis.windows-service.config

      1. 设置redis服务的密码,查找到requirepass foobared这一行,在下一行添加requirepass 123456,如下

      2. requirepass 123456

    2. redis-server.exe

      1. redis数据库的服务端,每次使用ip池都需要先双击启动它
    3. redis-cli.exe

      1. redis客户端,双击启动
      2. 输入ping,回车后显示PONG,则表示redis服务器启动成功
      3. 设置密码为123456:config set requirepass 123456
      4. 若没有设置,在运行项目的时候可能会报错:redis.exceptions.AuthenticationError: Client sent AUTH, but no password is set

更新setting.py配置文件

  • 配置redis数据库
    • 123456:是redis数据库密码(稍后会配置密码)
    • 127.0.0.1:6379:是redis数据库ip与端口
1
DB_CONN = 'redis://:123456@127.0.0.1:6379'

启动项目

每次都需要

每次都需要

  1. 双击运行redis-server.exe
  2. 双击运行redis-cli.exe,输入命令config set requirepass 123456
1
2
3
4
5
6
7
8
9
# 如果已经具备运行条件, 可用通过proxyPool.py启动。
# 程序分为: schedule 调度程序 和 server Api服务
# 分别在两个命令行窗口执行

# 启动调度程序
python proxyPool.py schedule

# 启动webApi服务
python proxyPool.py server

接口文档(Api)

启动web服务后, 默认配置下会开启 http://127.0.0.1:5010 的api接口服务:

api method Description params
/ GET api介绍 None
/get GET 随机获取一个代理 可选参数: ?type=https 过滤支持https的代理
/pop GET 获取并删除一个代理 可选参数: ?type=https 过滤支持https的代理
/all GET 获取所有代理 可选参数: ?type=https 过滤支持https的代理
/count GET 查看代理数量 None
/delete GET 删除代理 ?proxy=host:ip
  • 爬虫使用

如果要在爬虫代码中使用的话, 可以将此api封装成函数直接使用,例如:

requests.get里面的url是测试当前爬虫所处的ip地址,即res的值为当前ip地址(用于测试ip池)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import requests

def 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 code

def getHtml():
# ....
retry_count = 5
proxy = get_proxy().get("proxy")
while retry_count > 0:
try:
# 使用代理访问
html = requests.get('http://icanhazip.com/', proxies={"http": "http://{}".format(proxy)})
return html
except Exception:
retry_count -= 1
# 删除代理池中代理
delete_proxy(proxy)
return None

res=getHtml()
print(res.text)
1
2
3
4
5
import requests

# 关闭代理池测试ip地址
html = requests.get('http://icanhazip.com/')
print(html.text)