utilFunction.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. """
  4. -------------------------------------------------
  5. File Name: utilFunction.py
  6. Description : tool function
  7. Author : JHao
  8. date: 2016/11/25
  9. -------------------------------------------------
  10. Change Activity:
  11. 2016/11/25: 添加robustCrawl、verifyProxy、getHtmlTree
  12. -------------------------------------------------
  13. """
  14. # noinspection PyPep8Naming
  15. def robustCrawl(func):
  16. def decorate(*args, **kwargs):
  17. try:
  18. return func(*args, **kwargs)
  19. except Exception as e:
  20. print u"sorry, 抓取出错。错误原因:"
  21. print e
  22. return decorate
  23. def verifyProxy(proxy):
  24. """
  25. 检查代理格式
  26. :param proxy:
  27. :return:
  28. """
  29. import re
  30. verify_regex = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}"
  31. return True if re.findall(verify_regex, proxy) else False
  32. def getHtmlTree(url, **kwargs):
  33. """
  34. 获取html树
  35. :param url:
  36. :param kwargs:
  37. :return:
  38. """
  39. import requests
  40. from lxml import etree
  41. header = {'Connection': 'keep-alive',
  42. 'Cache-Control': 'max-age=0',
  43. 'Upgrade-Insecure-Requests': '1',
  44. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko)',
  45. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  46. 'Accept-Encoding': 'gzip, deflate, sdch',
  47. 'Accept-Language': 'zh-CN,zh;q=0.8',
  48. }
  49. html = requests.get(url=url, headers=header, timeout=30).content
  50. return etree.HTML(html)