utilFunction.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # -*- coding: utf-8 -*-
  2. """
  3. -------------------------------------------------
  4. File Name: utilFunction.py
  5. Description : 工具函数
  6. Author : JHao
  7. date: 2016/11/25
  8. -------------------------------------------------
  9. Change Activity:
  10. 2016/11/25: 添加robustCrawl、verifyProxy、getHtmlTree
  11. -------------------------------------------------
  12. """
  13. # noinspection PyPep8Naming
  14. def robustCrawl(func):
  15. def decorate(*args, **kwargs):
  16. try:
  17. return func(*args, **kwargs)
  18. except Exception as e:
  19. print u"sorry, 抓取出错。错误原因:"
  20. print e
  21. return decorate
  22. def verifyProxy(proxy):
  23. """
  24. 检查代理格式
  25. :param proxy:
  26. :return:
  27. """
  28. import re
  29. verify_regex = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,4}"
  30. return True if re.findall(verify_regex, proxy) else False
  31. def getHtmlTree(url, **kwargs):
  32. """
  33. 获取html树
  34. :param url:
  35. :param kwargs:
  36. :return:
  37. """
  38. import requests
  39. from lxml import etree
  40. html = requests.get(url=url).content
  41. return etree.HTML(html)