我有一个设置,在这里,我打印页面为pdf使用selenium+gecko。但是,无论我做什么,它似乎不尊重我设置的download.dir
选项或下载文件名。
以下是我的设置:
self.profile = webdriver.FirefoxProfile()
self.headers = {'User-Agent' : uagent, \
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', \
'Accept-Language' : 'en-gb,en;q=0.5', \
'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', \
'Keep-Alive' : '115', \
'Connection' : 'keep-alive', \
'Cache-Control' : 'max-age=0'}
self.profile.set_preference('browser.link.open_newwindow', 1)
self.profile.set_preference("general.useragent.override", uagent)
self.profile.set_preference("browser.download.manager.showWhenStarting", False)
self.profile.set_preference("browser.download.dir", '/home/foo/')
self.profile.set_preference("print_printer", "Mozilla Save to PDF")
self.profile.set_preference("print.always_print_silent", True)
self.profile.set_preference("print.show_print_progress", False)
self.profile.set_preference('print.save_as_pdf.links.enabled', True)
self.profile.set_preference("print.printer_Mozilla_Save_to_PDF.print_to_file", True)
self.profile.set_preference("print.printer_Mozilla_Save_to_PDF.print_to_filename", "file.pdf")
self.binary = FirefoxBinary('/path/to/Downloads/dir/firefox/firefox')
我也尝试过:
self.profile.set_preference("print.print_to_filename", "file.pdf")
为了打印,我会:
browser = webdriver.Firefox(firefox_profile=self.profile, \
firefox_binary=self.binary, executable_path='/some/path/dir/and/orm/driver/geckodriver')
browser.execute_script("window.print();")
当我执行这个命令时,我会在我执行脚本的目录中得到PDF,并且总是以mozilla.pdf
的形式执行,我不知道使用什么设置来更改它。
我试图更改页面名,以查看这是否会产生任何效果,但仍然以mozilla.pdf
的形式打印出来。
所以,我正在寻找一种解决办法,可以:
的名称
:(
发布于 2022-03-27 21:32:10
你差点就到了。一旦您通过update_preferences()
配置了所有设置,最后您必须使用set_preference()
,如下所示:
self.profile.update_preferences()
参考文献
您可以在以下网站找到几个相关的详细讨论:
发布于 2022-05-18 16:05:30
要解决这个问题,您需要将路径&文件名作为一个。
下面的
options
,您的例子是使用self
,但是想法是相同的!需要注意的是,打印会将PDF扫描为图像,然后不能高亮显示文本.
url = '<__some_public_pdf_URL_here__>'
out_dir = './data/' # whatever your outdir is for the printed file
out_filename = 'file.pdf'
out_path = out_dir + out_filename
options = FirefoxOptions()
options.add_argument("--start-maximized")
options.set_preference("print.always_print_silent", True)
options.set_preference("print.printer_Mozilla_Save_to_PDF.print_to_file", True)
# this line should guarantee export to correct dir & filename
options.set_preference('print.printer_Mozilla_Save_to_PDF.print_to_filename', '{}'.format(out_path))
options.set_preference("print_printer", "Mozilla Save to PDF")
driver = webdriver.Firefox(options=options)
try:
driver.get(url)
sleep(3) # give the browser a chance to load PDF
driver.execute_script('window.print();')
sleep(10) # give the PDF a chance to print, 10 seconds should be enough
driver.close()
except:
print('oops! failed for {}'.format(url)
https://stackoverflow.com/questions/71640257
复制相似问题