如何从抓取的链接 [Python] 下载 PDF?

How to Download PDFs from Scraped Links [Python]?

我正在 Python 中制作一个 PDF Web Scraper。本质上,我试图从我的一门课程中抓取所有的讲义,这些讲义都是 PDF 格式的。我想输入一个 url,然后获取 PDF 并将它们保存在笔记本电脑的一个目录中。我看过几个教程,但我不完全确定如何去做。 None Whosebug 上的问题似乎也对我有帮助。

这是我目前的情况:

import requests
from bs4 import BeautifulSoup
import shutil

bs = BeautifulSoup

url = input("Enter the URL you want to scrape from: ")
print("")

suffix = ".pdf"

link_list = []

def getPDFs():    
    # Gets URL from user to scrape
    response = requests.get(url, stream=True)
    soup = bs(response.text)

    #for link in soup.find_all('a'): # Finds all links
     #   if suffix in str(link): # If the link ends in .pdf
      #      link_list.append(link.get('href'))
    #print(link_list)

    with open('CS112.Lecture.09.pdf', 'wb') as out_file:
        shutil.copyfileobj(response.raw, out_file)
    del response
    print("PDF Saved")

getPDFs()

本来我已经得到了所有PDF的链接,但是不知道怎么下载;该代码现已被注释掉。

现在我已经到了尝试只下载一个 PDF 的地步;确实下载了一个 PDF,但它是一个 0KB 文件。

如果有用的话,我用的是Python3.4.2

如果不需要登录,可以使用urlretrieve():

from urllib.request import urlretrieve

for link in link_list:
    urlretrieve(link)