PyProxy——一款Python用的代理池工具

山屿云   ·   发表于 2022-08-21 22:04:33   ·   安全工具

1.工具介绍

  • 目前接入两个免费代理IP网站
  • 使用API接口进行调用
  • 使用Redis 进行数据存储
  • 进行类封装,便于维护阅读
  • 自动去重,以及校验可用IP

2. 开发原理

2.1 代理IP爬取

  • 使用线程池提高爬取速度
  • 存储到redis数据库,并且使用有序集合进行存储,自动去重
  1. # -*- coding:utf-8 -*-
  2. # 这里负责代理IP的采集工作
  3. from proxy_redis import ProxyRedis
  4. from multiprocessing import Process
  5. from concurrent.futures import ThreadPoolExecutor
  6. import requests
  7. from lxml import etree
  8. import time
  9. headers = {
  10. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
  11. }
  12. def get_kuai_ip(red):
  13. for i in range(1, 100):
  14. url = f'https://free.kuaidaili.com/free/intr/{i}/'
  15. resp = requests.get(url=url, headers=headers)
  16. tree = etree.HTML(resp.text)
  17. trs = tree.xpath('//table//tr')
  18. for tr in trs:
  19. ip = tr.xpath('./td[1]/text()') # IP
  20. port = tr.xpath('./td[2]/text()') # PORT
  21. if not ip:
  22. continue
  23. ip = ip[0]
  24. port = port[0]
  25. proxy_ip = ip + ':' + port
  26. # print(proxy_ip)
  27. red.add_proxy_ip(proxy_ip) # 增加新的ip地址
  28. time.sleep(20)
  29. def get_buzhidao_ip(red):
  30. url = 'https://ip.jiangxianli.com/?page=1'
  31. resp = requests.get(url=url, headers=headers)
  32. tree = etree.HTML(resp.text)
  33. trs = tree.xpath('//table//tr')
  34. for tr in trs:
  35. ip = tr.xpath('./td[1]/text()')
  36. port = tr.xpath('./td[2]/text()')
  37. if not ip:
  38. continue
  39. ip = ip[0]
  40. port = port[0]
  41. proxy_ip = ip + ':' + port
  42. # print(proxy_ip)
  43. red.add_proxy_ip(proxy_ip) # 增加新的ip地址
  44. def run(): # 启动
  45. red = ProxyRedis() # 创建好red存储
  46. t = ThreadPoolExecutor(2)
  47. while True:
  48. try:
  49. t.submit(get_kuai_ip, red) # 采集快代理
  50. t.submit(get_buzhidao_ip, red)
  51. except Exception as e:
  52. print('出现错误 >> ', e)
  53. continue
  54. time.sleep(60) # 每分钟跑一次
  55. if __name__ == '__main__':
  56. run()

2.2 代理IP校验

  • 使用Async异步爬虫提高IP验证速度
  • 验证原理
    • 使用代理IP访问百度
  1. # -*- coding:utf-8 -*-
  2. # 负责IP代理的验证工作
  3. import time
  4. from proxy_redis import ProxyRedis
  5. import asyncio
  6. import aiohttp
  7. async def verify_one(ip, sem, red):
  8. timeout = aiohttp.ClientTimeout(total=10) # 10s 没回来就报错
  9. async with sem:
  10. try:
  11. async with aiohttp.ClientSession() as session:
  12. async with session.get("http://www.baidu.com", proxy="http://" + ip, timeout=timeout) as resp:
  13. page_source = await resp.text()
  14. if resp.status in [200, 302]:
  15. print('[*]此IP可用 >> ', ip)
  16. red.set_max_score(ip)
  17. else:
  18. # 有问题,扣分
  19. print('[-]此IP不可用 >> ', ip)
  20. red.des_incrby(ip)
  21. except Exception as e:
  22. print('[-]此IP不可用 >> ', ip)
  23. red.desc_incrby(ip)
  24. async def main(red):
  25. # 1.把ip全部取出
  26. all_proxies = red.get_all_proxy()
  27. sem = asyncio.Semaphore(30)
  28. tasks = []
  29. for ip in all_proxies:
  30. tasks.append(asyncio.create_task(verify_one(ip, sem, red)))
  31. await asyncio.wait(tasks)
  32. def run():
  33. red = ProxyRedis()
  34. time.sleep(10)
  35. while True:
  36. try:
  37. asyncio.run(main(red))
  38. time.sleep(100)
  39. except Exception as e:
  40. print('出现错误 >> ', e)
  41. time.sleep(100)
  42. if __name__ == '__main__':
  43. run()

2.3 提供API接口访问

  • 使用 sanic 库,提供Api接口
  1. # -*- coding:utf-8 -*-
  2. # 负责提供代理IP的接口
  3. from proxy_redis import ProxyRedis
  4. from sanic import Sanic, json
  5. from sanic_cors import CORS
  6. from settings import *
  7. red = ProxyRedis()
  8. app = Sanic('IP')
  9. CORS(app)
  10. @app.route('/')
  11. def clhttp(req):
  12. ip = red.get_keyong_proxy()
  13. return json({'ip': ip})
  14. def run():
  15. app.run(host=API_ADDRESS, port=API_PORT)
  16. if __name__ == '__main__':
  17. run()

以上都是代理池的主要功能代码

3. 如何使用

  • 首先安装 Redis,开启Redis服务
  • settings.py文件中设置必要参数

  • 一般来讲,设置这几个就行
  • 设置完成之后,直接运行 runner.py 文件即可

  • 运行效果

  • 访问你设置的API接口,即可拿到代理IP

注意!注意!运行不来看看是不是缺少了库,如果仍有问题,可在论坛私聊

用户名金币积分时间理由
Track-劲夫 100.00 0 2022-08-23 11:11:14 一个受益终生的帖子~~

打赏我,让我更有动力~

附件列表

PyProxy.zip   文件大小:0.005M (下载次数:26)

4 条回复   |  直到 2022-8-31 | 1370 次浏览

山屿云
发表于 2022-8-23

JF我蹲你

评论列表

  • 加载数据中...

编写评论内容

喜欢悠哉独自在
发表于 2022-8-25

评论列表

  • 加载数据中...

编写评论内容

山屿云
发表于 2022-8-31

评论列表

  • 加载数据中...

编写评论内容

lilei029
发表于 2022-8-31

niu

评论列表

  • 加载数据中...

编写评论内容
登录后才可发表内容
返回顶部 投诉反馈

© 2016 - 2024 掌控者 All Rights Reserved.