utilFunction.py 2.2 KB

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