Guest User

Untitled

a guest
Jan 18th, 2020
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import re
  4. import lxml
  5. from pathlib import Path
  6. import sys
  7. import time
  8.  
  9. url = "https://github.com/wangzhengya/allitebooks/tree/master/results"
  10. html = requests.get(url)
  11. print(html.status_code, html.url)
  12. soup = BeautifulSoup(html.content, 'lxml')
  13. sources_list = []
  14.  
  15. for link in soup.findAll('a', attrs={'href': re.compile('/wangzhengya/allitebooks/blob/master/results/')}):
  16.     source = ('https://github.com' + link.get('href'))
  17.     sources_list.append(source)
  18.  
  19.  
  20. def downloader(url, folder):
  21.     path_to_folder = Path.home() / 'downloads' / 'pdf-books' / folder
  22.     path_to_folder.mkdir(exist_ok=True, parents=True)
  23.     pdf_file = url.split('/')[-1]
  24.  
  25.     check_for_existance_FILE = Path.joinpath(path_to_folder, pdf_file)
  26.    
  27.     if check_for_existance_FILE.is_file() is False:
  28.         try:
  29.             pdf = requests.get(url)
  30.             print(pdf.status_code, pdf.url)
  31.             with open(Path.joinpath(path_to_folder, pdf_file), 'wb') as FILE:
  32.                 FILE.write(pdf.content)
  33.  
  34.             print(str(pdf_file) + ' copied to ' + str(folder))
  35.  
  36.             time.sleep(2)
  37.  
  38.         except:
  39.             e = sys.exc_info()[0]
  40.             print("An exception occurred:")
  41.             print(e)
  42.  
  43.     else:
  44.         print('File already downloaded -> ' + str(check_for_existance_FILE))
  45.  
  46. def get_file_urls_from_source(source):
  47.     folder = source.split('/')[-1].split('.')[-2]
  48.  
  49.     try:
  50.         pdf_urls = requests.get(source)
  51.         print(pdf_urls.status_code, pdf_urls.url)
  52.         soup = BeautifulSoup(pdf_urls.content, 'lxml')
  53.  
  54.         for link in soup.findAll('td', attrs={'class': re.compile('blob-code blob-code-inner js-file-line')}):
  55.             pdf = (link.get_text())
  56.            
  57.             downloader(pdf, folder)
  58.  
  59.     except:
  60.         e = sys.exc_info()[0]
  61.         print("An exception occurred while connecting to GIThub:")
  62.         print(e)
  63.         time.sleep(60)
  64.  
  65.  
  66. for i, source in enumerate(sources_list[2:]):
  67.     print(i+1, source)
  68.     get_file_urls_from_source(source)
Advertisement
Add Comment
Please, Sign In to add comment