getFreeProxy.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. """
  3. -------------------------------------------------
  4. File Name: getFreeProxy.py
  5. Description : 抓取免费代理
  6. Author : JHao
  7. date: 2016/11/25
  8. -------------------------------------------------
  9. Change Activity:
  10. 2016/11/25:
  11. -------------------------------------------------
  12. """
  13. import re
  14. import requests
  15. from lxml import etree
  16. def robust(func):
  17. def decorate(*args, **kwargs):
  18. try:
  19. return func(*args, **kwargs)
  20. except Exception as e:
  21. print u"sorry, 抓取出错。错误原因:"
  22. print e
  23. return decorate
  24. def verifyProxy(proxy):
  25. """
  26. 检查代理格式
  27. :param proxy:
  28. :return:
  29. """
  30. verify_regex = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,4}"
  31. return True if re.findall(verify_regex, proxy) else False
  32. # 快代理
  33. # noinspection PyPep8Naming
  34. @robust
  35. def freeProxyFirst(page=10):
  36. """
  37. 抓取快代理IP http://www.kuaidaili.com/
  38. :param page: 翻页数
  39. :return:
  40. """
  41. url_list = ('http://www.kuaidaili.com/proxylist/{page}/'.format(page=page) for page in range(1, page + 1))
  42. # 页数不用太多, 后面的全是历史IP, 可用性不高
  43. for url in url_list:
  44. html = requests.get(url).content
  45. tree = etree.HTML(html)
  46. proxy_list = tree.xpath('.//div[@id="index_free_list"]//tbody/tr')
  47. for proxy in proxy_list:
  48. yield ':'.join(proxy.xpath('./td/text()')[0:2])
  49. # 代理66
  50. @robust
  51. def freeProxySecond(proxy_number):
  52. """
  53. 抓取代理66 http://www.66ip.cn/
  54. :param proxy_number: 代理数量
  55. :return:
  56. """
  57. pass
  58. if __name__ == '__main__':
  59. # for e in freeProxyFirst():
  60. # print e
  61. pass