utilFunction.py 2.7 KB

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