utilFunction.py 2.8 KB

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