Skip to content

Instantly share code, notes, and snippets.

@CrazyCoder
Last active September 23, 2022 18:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrazyCoder/2e2788c1542b93869c8b31948cde198a to your computer and use it in GitHub Desktop.
Save CrazyCoder/2e2788c1542b93869c8b31948cde198a to your computer and use it in GitHub Desktop.
# 1. Open https://link.springer.com/search/page/1?facet-content-type=%22Book%22&package=mat-covid19_textbooks
# 2. Click on the button on the top right of the table to save results into CSV file (SearchResults.csv)
# 3. Run: python springer.py SearchResults.csv
# Note: Python 3 is needed, `pip install requests` if the module is missing
import sys
import csv
import requests
from pathlib import Path
from os import path
import re
def get_valid_filename(s):
return re.sub(r'(?u)[^- \w.]', '', s.strip())
def download_file(ext):
try:
if path.exists(f'{file_name}.{ext}'):
print(f'EXISTS: {file_name}.{ext}')
return
print(f'Downloading {ext.upper()}')
ctx = "content" if ext == "pdf" else "download"
url = f'https://link.springer.com/{ctx}/{ext}/{row["Item DOI"]}.{ext}'
content = requests.get(url)
if len(content.content) < 500:
raise Exception(f'Not a {ext.upper()}')
open(f'{file_name}.{ext}', 'wb').write(content.content)
except:
print(f'Failed to download {ext.upper()} for {row["Item Title"]} by {row["Authors"]}')
if __name__ == '__main__':
with open(sys.argv[1], encoding='utf-8') as csv_file:
csv = csv.DictReader(csv_file, delimiter=",", quoting=csv.QUOTE_ALL)
next(csv)
for row in csv:
print(f'Processing: "{row["Item Title"]} by {row["Authors"]}"')
file_name = f'{Path(sys.argv[1]).parent}/' + get_valid_filename(f'{row["Item Title"]} - {row["Authors"]}')
download_file("pdf")
download_file("epub")
@xonika9
Copy link

xonika9 commented May 16, 2020

Привет!

Хочу скачать с помощью вашего кода книги. Я не программист, но книжки почитать хочется. Скачал Python 3.8.3 с офф сайта, скачал VS Code, установил плагин python, ввел "pip install requests", установилась 20 версия.
Далее делаю по инструкции:

  1. Скачал SearchResults.csv с Springer
  2. Запускаю в терминале "python E:\Загрузки\389\springer.py E:\Загрузки\389\SearchResults.csv", идет загрузка, но все файлы скачиваются размером 14КБ и не открываются.

Подскажите, пожалуйста, что делаю не так?

@CrazyCoder
Copy link
Author

Попробуйте скачать вручную, похоже, там добавили проверку на роботов: https://i.imgur.com/Z6b7po2.png.

Если после прохождения проверки проблема со скриптом повторяется, боюсь, скрипт теперь бесполезен.

@Shtihl
Copy link

Shtihl commented May 16, 2020

Возможно есть смысл попробовать подсовывать реквест с заголовками из браузера, на котором проверка пройдена, и может сделать задержку между скачиванием файлов. Жаль, что моих навыков пока хватает на копи&пэйст&ран, не уверен, что смог бы подрихтовать запрос

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment