How to download PDF files from a list of URLs in Python?

Question:

I have a big list of links to PDF files that I need to download (500+) and I was trying to make a program to download them all because I don’t want to manually do them.

This is what I have and when I try to run it, the console just opens up and closes.

import wget

def main():
    f = open("list.txt", "r")

    f1 = f.readlines()
    for x in f1:
        wget.download(x, 'C:/Users/ALEXJ/OneDrive/Desktop/Books')
        print("Downloaded" + x)
Asked By: Alex S.

||

Answers:

Make sure you add the function call at the end of your script, is good practice to use the if __name__ == '__main__': before the code of code you want to execute (although is not mandatory it will help so if you import this file into another your code will not get executed without your knowledge)

if __name__ == '__main__':
    main()
Answered By: Alvaro Bataller

The problem is that you are defining the function main() but you are not calling it anywhere else.

Here is a complete example to achieve what you want:

import wget


def main():
    books_folder = 'C:/Users/ALEXJ/OneDrive/Desktop/Books'
    books_list = 'list.txt'

    with open(books_list) as books:
        for book in books:
            wget.download(book.strip(), books_folder)
            print('Downloaded', book)


if __name__ == '__main__':
    main()
Answered By: accdias
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.