utils.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import requests
  2. import asyncio
  3. import aiohttp
  4. from requests.exceptions import ConnectionError
  5. base_headers = {
  6. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36',
  7. 'Accept-Encoding': 'gzip, deflate, sdch',
  8. 'Accept-Language': 'zh-CN,zh;q=0.8'
  9. }
  10. def get_page(url, options={}):
  11. headers = dict(base_headers, **options)
  12. print('Getting', url)
  13. try:
  14. r = requests.get(url, headers=headers)
  15. print('Getting result', url, r.status_code)
  16. if r.status_code == 200:
  17. return r.text
  18. except ConnectionError:
  19. print('Crawling Failed', url)
  20. return None
  21. class Downloader(object):
  22. """
  23. 一个异步下载器,可以对代理源异步抓取,但是容易被BAN。
  24. """
  25. def __init__(self, urls):
  26. self.urls = urls
  27. self._htmls = []
  28. async def download_single_page(self, url):
  29. async with aiohttp.ClientSession() as session:
  30. async with session.get(url) as resp:
  31. self._htmls.append(await resp.text())
  32. def download(self):
  33. loop = asyncio.get_event_loop()
  34. tasks = [self.download_single_page(url) for url in self.urls]
  35. loop.run_until_complete(asyncio.wait(tasks))
  36. @property
  37. def htmls(self):
  38. self.download()
  39. return self._htmls