utilFunction.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. return True if re.findall(verify_regex, proxy) else False
  39. # noinspection PyPep8Naming
  40. def getHtmlTree(url, **kwargs):
  41. """
  42. 获取html树
  43. :param url:
  44. :param kwargs:
  45. :return:
  46. """
  47. header = {'Connection': 'keep-alive',
  48. 'Cache-Control': 'max-age=0',
  49. 'Upgrade-Insecure-Requests': '1',
  50. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko)',
  51. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  52. 'Accept-Encoding': 'gzip, deflate, sdch',
  53. 'Accept-Language': 'zh-CN,zh;q=0.8',
  54. }
  55. # TODO 取代理服务器用代理服务器访问
  56. wr = WebRequest()
  57. # delay 2s for per request
  58. time.sleep(2)
  59. html = wr.get(url=url, header=header).content
  60. return etree.HTML(html)
  61. def tcpConnect(proxy):
  62. """
  63. TCP 三次握手
  64. :param proxy:
  65. :return:
  66. """
  67. from socket import socket, AF_INET, SOCK_STREAM
  68. s = socket(AF_INET, SOCK_STREAM)
  69. ip, port = proxy.split(':')
  70. result = s.connect_ex((ip, int(port)))
  71. return True if result == 0 else False
  72. # noinspection PyPep8Naming
  73. def validUsefulProxy(proxy):
  74. """
  75. 检验代理是否可用
  76. :param proxy:
  77. :return:
  78. """
  79. if isinstance(proxy, bytes):
  80. proxy = proxy.decode('utf8')
  81. proxies = {"http": "http://{proxy}".format(proxy=proxy)}
  82. try:
  83. # 超过20秒的代理就不要了
  84. r = requests.get('http://httpbin.org/ip', proxies=proxies, timeout=20, verify=False)
  85. if r.status_code == 200:
  86. logger.info('%s is ok' % proxy)
  87. return True
  88. except Exception as e:
  89. logger.debug(e)
  90. return False