回答问题

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

这是我到目前为止所拥有的:

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 文件。

如果有任何用处,我使用的是 Python 3.4.2

Answers

如果这是不需要登录的东西,您可以使用urlretrieve():

from urllib.request import urlretrieve

for link in link_list:
    urlretrieve(link)
Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐