how-to_use.rst 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. .. how_to_use
  2. 如何使用
  3. ----------
  4. 爬虫代码要对接代理池目前有两种方式: 一是通过调用API接口使用, 二是直接读取数据库.
  5. 调用API
  6. >>>>>>>>>
  7. 启动ProxyPool的 ``server`` 后会提供如下几个http接口:
  8. ============ ======== ================ ==============
  9. Api Method Description Arg
  10. ============ ======== ================ ==============
  11. / GET API介绍 无
  12. /get GET 随机返回一个代理 无
  13. /get_all GET 返回所有代理 无
  14. /get_status GET 返回代理数量 无
  15. /delete GET 删除指定代理 proxy=host:ip
  16. ============ ======== ================ ==============
  17. 在代码中可以通过封装上面的API接口来使用代理, 例子:
  18. .. code-block:: python
  19. import requests
  20. def get_proxy():
  21. return requests.get("http://127.0.0.1:5010/get/").json()
  22. def delete_proxy(proxy):
  23. requests.get("http://127.0.0.1:5010/delete/?proxy={}".format(proxy))
  24. # your spider code
  25. def getHtml():
  26. # ....
  27. retry_count = 5
  28. proxy = get_proxy().get("proxy")
  29. while retry_count > 0:
  30. try:
  31. # 使用代理访问
  32. html = requests.get('http://www.example.com', proxies={"http": "http://{}".format(proxy)})
  33. return html
  34. except Exception:
  35. retry_count -= 1
  36. # 删除代理池中代理
  37. delete_proxy(proxy)
  38. return None
  39. 本例中我们在本地 ``127.0.0.1`` 启动端口为 ``5010`` 的 ``server``, 使用 ``/get`` 接口获取代理, ``/delete`` 删除代理.
  40. 读数据库
  41. >>>>>>>>>
  42. 目前支持配置两种数据库: ``REDIS`` 、 ``SSDB``.
  43. * **REDIS** 储存结构为 ``hash``, hash name为配置项中的 **TABLE_NAME**
  44. * **SSDB** 储存结构为 ``hash``, hash name为配置项中的 **TABLE_NAME**
  45. 可以在代码中自行读取.