iama_alpaca

FW_Scraper.py

Oct 6th, 2017
915
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. #! /usr/bin/env python3
  2.  
  3. from bs4 import BeautifulSoup as bs4
  4. import requests
  5. import os
  6. import time
  7.  
  8. # Making a folder in which to put the threads' html files
  9. if not os.path.exists("Threads"):
  10.     os.makedirs("Threads")
  11.  
  12. # Setting user agent to standard Firefox-on-Windows because the site blocks the script otherwise
  13. headers = {
  14.     'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
  15. }
  16.  
  17. # Checking to see how many pages there are total so the main loop can have a definite end
  18. pages_check = requests.get("https://www.fatwallet.com/forums/search/results.php?&type=forums&query=&sort=&match=titleop&forum=52&active=all&newsort=date", headers=headers)
  19. pages_soup = bs4(pages_check.text, 'html.parser')
  20. pages_buttons= pages_soup.select('.standardPageSection .pageLink')
  21. pages = int(pages_buttons[-1].text.replace(',',''))
  22.  
  23. # Checks file to see last page completed. Used for resuming in the event that the download was stopped
  24. if os.path.isfile('latest_page_done.txt'):
  25.     start_page = int(open('latest_page_done.txt', 'r').read()) + 1
  26. else:
  27.     start_page = 1
  28.  
  29. print('Beginning download at page {}'.format(start_page))
  30.  
  31. # Main loop for downloading threads
  32. for p in range(start_page,pages+1):
  33.     res = requests.get("https://www.fatwallet.com/forums/search/results.php?page="+str(p)+"&type=forums&query=&sort=&match=titleop&forum=52&active=all&newsort=date", headers=headers)
  34.     soup = bs4(res.text, 'html.parser')
  35.     threads = soup.select('.forumTopicListBNS .forumTopicTitle')
  36.     for i in threads:
  37.         threadid = i['href'].split('/')[-1]
  38.         if not os.path.isfile('Threads/'+threadid+'.html'):
  39.             print('Downloading Thread: ID {}'.format(threadid))
  40.             threadlink = 'https://www.fatwallet.com/forums/textthread.php?catid=52&threadid='+threadid
  41.             res2 = requests.get(threadlink, headers=headers)
  42.             with open('Threads/'+threadid+'.html', 'w') as f:
  43.                 f.write(res2.text)
  44.             time.sleep(0.3)
  45.     print('Page {} finished; Starting page {}'.format(p, p+1))
  46.     with open("latest_page_done.txt", 'w') as f:
  47.         f.write(str(p))
Advertisement
Add Comment
Please, Sign In to add comment