utilFunction.py 2.7 KB

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