我正在用 Python 制作一个 PDF Web Scraper。本质上,我试图从我的一门类(class)中抓取所有的讲义,这些讲义都是 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
最佳答案
如果这是不需要登录的东西,你可以使用urlretrieve()
:
from urllib.request import urlretrieve
for link in link_list:
urlretrieve(link)
关于python - 如何从抓取的链接 [Python] 下载 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29641671/