utilFunction.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 lxml import etree
  16. from Util.LogHandler import LogHandler
  17. from Util.WebRequest import WebRequest
  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. # noinspection PyPep8Naming
  38. def verifyProxyFormat(proxy):
  39. """
  40. 检查代理格式
  41. :param proxy:
  42. :return:
  43. """
  44. import re
  45. verify_regex = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}"
  46. return True if re.findall(verify_regex, proxy) else False
  47. # noinspection PyPep8Naming
  48. def getHtmlTree(url, **kwargs):
  49. """
  50. 获取html树
  51. :param url:
  52. :param kwargs:
  53. :return:
  54. """
  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. wr = WebRequest()
  65. html = wr.get(url=url, header=header).content
  66. return etree.HTML(html)
  67. # noinspection PyPep8Naming
  68. def validUsefulProxy(proxy):
  69. """
  70. 检验代理是否可用
  71. :param proxy:
  72. :return:
  73. """
  74. proxies = {"https": "https://{proxy}".format(proxy=proxy)}
  75. try:
  76. # 超过40秒的代理就不要了
  77. r = requests.get('https://www.baidu.com', proxies=proxies, timeout=40, verify=False)
  78. if r.status_code == 200:
  79. logger.debug('%s is ok' % proxy)
  80. return True
  81. except Exception as e:
  82. logger.info(e)
  83. return False