utilFunction.py 2.6 KB

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