我需要一些自动脚本来打印页面。该脚本必须在 Chrome 上运行,因为 FF 无法为该打印任务提供合适的输出。我尝试了几件事,但由于某种原因它仍然需要文件名,并且它忽略了我用于 savefile.default_directory 和 download.default_directory 设置的内容。这是我当前正在处理的脚本(不用说,我尝试删除和添加部分,尝试将 TMP_DIR 设置为我的实际默认下载,等等)。
import json
from selenium import webdriver
def main():
TMP_DIR = "F:/Downloads"
printer = "Microsoft Print to PDF"
options = webdriver.ChromeOptions()
print_settings = {
"recentDestinations": [{
"id": printer,
"origin": "local",
"account": "",
}],
"selectedDestinationId": printer,
"version": 2,
"isHeaderFooterEnabled": False,
"isLandscapeEnabled": True
}
options.add_argument("--start-maximized")
options.add_argument('--window-size=1920,1080')
# options.add_argument("--headless")
options.add_argument('--enable-print-browser')
options.add_argument("--kiosk")
options.add_argument("--kiosk-printing")
options.add_argument("--safebrowsing-disable-download-protection");
options.add_argument("--safebrowsing-disable-extension-blacklist");
options.add_experimental_option("prefs", {
"printing.print_preview_sticky_settings.appState": json.dumps(print_settings),
"savefile.default_directory": TMP_DIR, # Change default directory for downloads
"download.default_directory": TMP_DIR, # Change default directory for downloads
"download.prompt_for_download": False, # To auto download the file
"download.directory_upgrade": True,
"profile.default_content_setting_values.automatic_downloads": 1,
"safebrowsing.enabled": True
})
driver = webdriver.Chrome(executable_path="C:/Users/97252/Downloads/chromedriver-win64/chromedriver-win64/chromedriver.exe",
chrome_options=options)
driver.get("https://www.google.com/")
driver.execute_script("window.print();")
if __name__ == '__main__':
main()
使用chrome/chromedriver 121.0.6167.184 Python 3.9.13 硒==3.11.0
我还能做些什么来强制下载吗?如果我可以设置文件名,那就太好了,但是在这一点上我会满足于任何事情。
找到了一个奇怪的解决方案,我不能说我喜欢。 为了防止出现对话框,chrome需要模拟手机。为什么?我不知道,但它有效。应用以下修复:
print_settings = {
"recentDestinations": [{
"id": "Save as PDF",
"origin": "local",
"account": ""
}],
"selectedDestinationId": "Save as PDF",
"version": 2,
"isHeaderFooterEnabled": False,
"mediaSize": { # for some reason, mobile printing assumes A5 papers.
"height_microns": 297000,
"name": "ISO_A4",
"width_microns": 210000,
"custom_display_name": "A4"
},
"customMargins": {},
"marginsType": 2,
"scaling": 175,
"scalingType": 3,
"scalingTypePdf": 3,
"isCssBackgroundEnabled": True
}
mobile_emulation = {
"deviceMetrics": { "width": 1024, "height": 600, "pixelRatio": 1.41 },
"userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
"clientHints": {"platform": "Android", "mobile": True}
}
options.add_experimental_option("mobileEmulation", mobile_emulation)