utilFunction.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. import requests
  15. from lxml import etree
  16. from Util.LogHandler import LogHandler
  17. from Util.WebRequest import WebRequest
  18. logger = LogHandler(__name__, stream=False)
  19. # noinspection PyPep8Naming
  20. def robustCrawl(func):
  21. def decorate(*args, **kwargs):
  22. try:
  23. return func(*args, **kwargs)
  24. except Exception as e:
  25. logger.info(u"sorry, 抓取出错。错误原因:")
  26. logger.info(e)
  27. return decorate
  28. # noinspection PyPep8Naming
  29. def verifyProxyFormat(proxy):
  30. """
  31. 检查代理格式
  32. :param proxy:
  33. :return:
  34. """
  35. import re
  36. verify_regex = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}"
  37. return True if re.findall(verify_regex, proxy) else False
  38. # noinspection PyPep8Naming
  39. def getHtmlTree(url, **kwargs):
  40. """
  41. 获取html树
  42. :param url:
  43. :param kwargs:
  44. :return:
  45. """
  46. header = {'Connection': 'keep-alive',
  47. 'Cache-Control': 'max-age=0',
  48. 'Upgrade-Insecure-Requests': '1',
  49. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko)',
  50. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  51. 'Accept-Encoding': 'gzip, deflate, sdch',
  52. 'Accept-Language': 'zh-CN,zh;q=0.8',
  53. }
  54. # TODO 取代理服务器用代理服务器访问
  55. wr = WebRequest()
  56. html = wr.get(url=url, header=header).content
  57. return etree.HTML(html)
  58. # noinspection PyPep8Naming
  59. def validUsefulProxy(proxy):
  60. """
  61. 检验代理是否可用
  62. :param proxy:
  63. :return:
  64. """
  65. if isinstance(proxy, bytes):
  66. proxy = proxy.decode('utf8')
  67. proxies = {"https": "https://{proxy}".format(proxy=proxy)}
  68. try:
  69. # 超过20秒的代理就不要了
  70. r = requests.get('https://www.baidu.com', proxies=proxies, timeout=20, verify=False)
  71. if r.status_code == 200:
  72. logger.info('%s is ok' % proxy)
  73. return True
  74. except Exception as e:
  75. logger.debug(e)
  76. return False