utilFunction.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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__)
  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. proxies = {"https": "https://{proxy}".format(proxy=proxy)}
  66. try:
  67. # 超过40秒的代理就不要了
  68. r = requests.get('https://www.baidu.com', proxies=proxies, timeout=40, verify=False)
  69. if r.status_code == 200:
  70. logger.debug('%s is ok' % proxy)
  71. return True
  72. except Exception as e:
  73. logger.info(e)
  74. return False