utilFunction.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. def tcpConnect(proxy):
  59. """
  60. TCP 三次握手
  61. :param proxy:
  62. :return:
  63. """
  64. from socket import socket, AF_INET, SOCK_STREAM
  65. s = socket(AF_INET, SOCK_STREAM)
  66. ip, port = proxy.split(':')
  67. result = s.connect_ex((ip, int(port)))
  68. return True if result == 0 else False
  69. # noinspection PyPep8Naming
  70. def validUsefulProxy(proxy):
  71. """
  72. 检验代理是否可用
  73. :param proxy:
  74. :return:
  75. """
  76. if isinstance(proxy, bytes):
  77. proxy = proxy.decode('utf8')
  78. proxies = {"http": "http://{proxy}".format(proxy=proxy)}
  79. try:
  80. # 超过20秒的代理就不要了
  81. r = requests.get('http://httpbin.org/ip', proxies=proxies, timeout=20, verify=False)
  82. if r.status_code == 200:
  83. logger.info('%s is ok' % proxy)
  84. return True
  85. except Exception as e:
  86. logger.debug(e)
  87. return False