在Selenium中的特定位置打印网页
我有这个代码去谷歌并将页面转换为PDF。
# Program to go to Google and convert the page to a PDF
# But it saves in my downloads folder (I want it in a particular folder in the directory I ran this code)
from selenium import webdriver
import json
# Set up web driver
options = webdriver.ChromeOptions()
options.headless = False
options.add_argument("--kiosk-printing")
settings = {
"recentDestinations": [{
"id": "Save as PDF",
"origin": "local",
"account": "",
'default_directory': 'folder' # This is the folder where i want to place my PDF (in the same directory as this
# file)
}],
"selectedDestinationId": "Save as PDF",
"version": 2,
}
prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(settings)}
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(executable_path="chromedriver.exe", options=options)
driver.get("https://google.com")
# This gets saved in my downloads folder
driver.execute_script("window.print();")
但我希望它保存在名为“文件夹”的文件夹中,该文件夹与此 Python 文件位于同一目录中。'default_directory': 'folder'不工作。
回答
options = webdriver.ChromeOptions()
options.headless = False
options.add_argument("--kiosk-printing")
options.add_argument("--kiosk")
options.add_argument("--kiosk-printing")
settings = {
"recentDestinations": [{
"id": "Save as PDF",
"origin": "local",
"account": "",
}],
"selectedDestinationId": "Save as PDF",
"version": 2,
}
prefs = {
'printing.print_preview_sticky_settings.appState': json.dumps(settings),
"savefile.default_directory": r"C:UserspraveDownloadstravelBAfolder",
}
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(executable_path="chromedriver.exe", options=options)
driver.get("https://google.com")
# This gets saved in my downloads folder
driver.execute_script("window.print();")
input()
使用 saveFile.default_directory