2016-09-21 73 views
0

我想要做的是循環訪問URL列表以下載一系列.pdf文件,並將它們保存爲.zip文件。目前我只想用一個URL來測試代碼。我得到的錯誤是:Python將PDF下載到.zip中

Traceback (most recent call last): 
    File "I:\test_pdf_download_zip.py", line 36, in <module> 
    zip_file(zipfile_name, url) 
    File "I:\test_pdf_download_zip.py", line 30, in zip_file 
    myzip.write(dowload_pdf(url)) 
TypeError: expected a string or other character buffer object 

會有人知道如何正確地傳遞.PDF請求的.zip(避免上述錯誤),以便我將其追加,或者知道這是可以做到的這個?

import os 
import zipfile 
import requests 

output = r"I:" 

# File name of the zipfile 
zipfile_name = os.path.join(output, "test.zip") 

# Random test pdf 
url = r"http://www.pdf995.com/samples/pdf.pdf" 

def create_zipfile(zipfile_name): 
    zipfile.ZipFile(zipfile_name, "w") 

def dowload_pdf(url): 
    response = requests.get(url, stream=True) 
    with open('test.pdf', 'wb') as f: 
     f.write(response.content) 

def zip_file(zip_name, url): 
    with open(zip_name,'a') as myzip: 
     myzip.write(dowload_pdf(url)) 

if __name__ == "__main__": 
    create_zipfile(zipfile_name) 
    zip_file(zipfile_name, url) 
    print("Done") 

回答

0

您的download_pdf()函數正在保存文件,但它不返回任何內容。您需要修改它,以便實際返回到myzip.write()的文件路徑。你不想硬編碼test.pdf,但傳遞獨特的路徑到你的下載功能,所以你不會在你的檔案中多個test.pdf

def dowload_pdf(url, path): 
    response = requests.get(url, stream=True) 
    with open(path, 'wb') as f: 
     f.write(response.content) 
    return path