[英]How to download a web page as a PDF using Python?
我想制作一個可以以PDF格式下載網站的腳本。 用戶應該能夠輸入URL( https://stackoverflow.com/ )和PDF的文件路徑,以將PDF下載到(c:\\ Bob \\ PDF)。
到目前為止,這是我的代碼:
import requests
import pdfkit
url = input("Please enter the url of the file you want to download.")
pdf = pdfkit.from_url(url, "file.pdf")
path = input("Please enter the file path that you would like the file to
download to. c:\Bob\PDF is an example of a valid file path.")
print("Download starting.")
r = requests.get(pdf)
with open(path, 'wb') as f:
f.write(r.content)
由於某些原因,PDF無法下載。 我認為我需要先將網頁轉換為HTML,然后再將其轉換為PDF,以便可以下載,但是我不確定如何進行此操作。 任何幫助是極大的贊賞。
首先方法
from_url from module 'pdfkit'
調用時返回True
。
執行此行后, pdf = pdfkit.from_url(url, "file.pdf")
的pdf
值為True
或False
具體取決於下載和創建文件。
因此,這行r = requests.get(pdf)
request.get r = requests.get(pdf)
被評估為r = requests.get(True)
無法正確執行。
基本上,您只需要詢問用戶URL和文件路徑
url = input("Please enter the url of the file you want to download.")
path = input("Please enter the file path ex. C:\Jim\Desktop")
file_name = input("Please enter file name")
if pdfkit.from_url(str(url), str(path + file_name)): # Check if method from_url returned True
print("Sucessfully created pdf from url")
else:
print("Something went wrong")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.