utils.py 1.4 KB

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