如何使用 Python 将网页下载为 PDF?

How to download a web page as a PDF using Python?

我想制作一个可以将网站下载为 PDF 的脚本。用户应该能够输入 URL (https://whosebug.com/) 和 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' 

returns True 调用时。

执行此行后 pdf = pdfkit.from_url(url, "file.pdf") pdf 的值是 TrueFalse 取决于下载和创建文件。

所以这一行 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")