我正在尝试使用 Python Selenium 将打印预览选项中的
Destination
从 Microsoft Print to PDF
更改为 Save as PDF
,然后单击“保存”按钮。save as PDF
。谁能帮我解决这个问题吗?代码:
import time, os
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from bs4 import BeautifulSoup
import pyautogui
import autoit
def main(PDF_URL):
options = webdriver.ChromeOptions()
path = str(os.path.dirname(os.path.abspath(__file__))) + "\download"
options.add_argument("--disable-popup-blocking")
options.add_argument("--disable-notifications")
options.add_argument("--disable-notifications")
# Bypass OS security model
options.add_argument("--no-sandbox")
# Run in headless mode (optional)
# options.add_argument("--headless")
options.add_argument("--disable-dev-shm-usage")
prefs = {'download.default_directory' : path,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True
}
options.add_experimental_option("prefs", prefs)
options.add_experimental_option('excludeSwitches', ['enable-logging'])
browser = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
browser.maximize_window()
browser.get(PDF_URL)
browser.implicitly_wait(180)
print("browser open successfully..")
browser.execute_script('window.print();')
time.sleep(5)
if __name__ == "__main__":
PDF_URL = "10.1055-s-2001-17364.pdf"
main(PDF_URL)
如果你想以编程方式从 URL 下载 pdf 文件,我想你甚至不必使用 selenium,你可以使用下面的代码轻松从 URL 下载并保存 pdf 文件:
import urllib.request
response = urllib.request.urlopen(URL)
file = open("FILENAME.pdf", 'wb')
file.write(response.read())
file.close()
如果您的页面是动态的或虚拟 DOM,这种方式不起作用,您 应该使用硒。
如果您的 URL 不是 pdf 文件,您可以搜索一些 将该页面内容转换为 pdf 的对话方法。