如何使用Selenium&#x2B更改保存的PDF PAGE名称Chromedrive

发布于 2025-01-21 11:06:09 字数 1567 浏览 0 评论 0原文

我有一个脚本,该脚本使用Selenium Python下载PDF页面根据此问题制作

目前我的目标是更改此文件的名称,以便将其定位为我选择的名称,然后更改已保存文件的目标文件夹。

我的疑问是: 我应该在哪里更改,以便使用我选择的名称保存文件?

即使对“ prefs =”变量的更改进行了更改,该文件仍将保存在默认的Chrome目录中。

目前,我有以下代码:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless') # Escondendo o navegador
driver = webdriver.Chrome(options=chrome_options)
driver.maximize_window()
settings = {
    "recentDestinations": [{
            "id": "Save as PDF",
            "origin": "local",
            "account": "",
        }],
        "isLandscapeEnabled": True,
        "selectedDestinationId": "Save as PDF",
        "version": 2,
    }

prefs = {
    "printing.print_preview_sticky_settings.appState": json.dumps(settings),
    "profile.default_content_settings.popups" : 0,

    "download.name":"name_file", # ?????? ESTE CÓDIGO NÃO ALTERA O NOME

    "download.default_directory": r'C:\Users\diretorio_escolhido\\' # ESTE CÓDIGO NÃO ALTERA O DESTINO,

    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
}


chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('--kiosk-printing')

driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get(name_Object.url)
sleep(5) # Pausa para carregar os dados
driver.execute_script('window.print();')

print('Gerou o PDF')

I have a script that uses Selenium Python to download a PDF page made based on this question

My goal at the moment is to change the name of this file so that it is located with the name I chose and then change the destination folder of the saved file.

My doubts are:
Where should I change so that the file is saved with the name I choose?

Even with the changes made to the "prefs=" variable, the file continues to be saved in the default chrome directory.

At the moment I have the following code:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless') # Escondendo o navegador
driver = webdriver.Chrome(options=chrome_options)
driver.maximize_window()
settings = {
    "recentDestinations": [{
            "id": "Save as PDF",
            "origin": "local",
            "account": "",
        }],
        "isLandscapeEnabled": True,
        "selectedDestinationId": "Save as PDF",
        "version": 2,
    }

prefs = {
    "printing.print_preview_sticky_settings.appState": json.dumps(settings),
    "profile.default_content_settings.popups" : 0,

    "download.name":"name_file", # ?????? ESTE CÓDIGO NÃO ALTERA O NOME

    "download.default_directory": r'C:\Users\diretorio_escolhido\\' # ESTE CÓDIGO NÃO ALTERA O DESTINO,

    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
}


chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('--kiosk-printing')

driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get(name_Object.url)
sleep(5) # Pausa para carregar os dados
driver.execute_script('window.print();')

print('Gerou o PDF')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蘸点软妹酱 2025-01-28 11:06:09

我面临同样的问题。目前,我找到了以下解决方法:

driver.execute_script("document.title = \'{}\'".format(filename))

I'm facing the same question. For now I found the following workaround:

driver.execute_script("document.title = \'{}\'".format(filename))
双马尾 2025-01-28 11:06:09

更改download.default_directory to savefile.default_directory,因此保存的位置可工作。

可悲的是,我认为下载前我们不能更改文件名,但是您可以在下载后重命名您的文件,通过重命名在下载文件夹中文件:

import os    
import shutil
download_folder = "C:\\Users\\username\\Downloads\\Test"
filename = max([download_folder + "\\" + f for f in os.listdir(Initial_path)],key=os.path.getctime)
shutil.move(filename,os.path.join(Initial_path,r"newPDFName.pdf"))

Change download.default_directory to savefile.default_directory so your saving location works.

Sadly I think we can't change the filename before download, but you can rename your file after download, by renaming the latest file in download folder:

import os    
import shutil
download_folder = "C:\\Users\\username\\Downloads\\Test"
filename = max([download_folder + "\\" + f for f in os.listdir(Initial_path)],key=os.path.getctime)
shutil.move(filename,os.path.join(Initial_path,r"newPDFName.pdf"))
彩扇题诗 2025-01-28 11:06:09

此答案使用 vimuth's 上面发布的建议,并且使用python 3.9.4

chrome_driver_path = ChromeDriverManager().install()
service = Service(chrome_driver_path)
service.start()

options = webdriver.ChromeOptions()
options.add_argument('--start-maximized')

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': download_path }

    options.add_experimental_option('prefs', prefs)
    options.add_argument('--kiosk-printing')

    driver = webdriver.Chrome(chrome_driver_path, options=options)

This answer is using vimuth's suggestion posted above, and it is fully worked for myself using Python 3.9.4

chrome_driver_path = ChromeDriverManager().install()
service = Service(chrome_driver_path)
service.start()

options = webdriver.ChromeOptions()
options.add_argument('--start-maximized')

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': download_path }

    options.add_experimental_option('prefs', prefs)
    options.add_argument('--kiosk-printing')

    driver = webdriver.Chrome(chrome_driver_path, options=options)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文