我有一个设置,使用selenium+gecko将页面打印为pdf。但是,无论我做什么,它似乎都不尊重我设置的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
所以,是的,我正在寻找一个解决方案,可以:
- 设置pdf的目录
- 设置pdf的名称
:(
你差不多到了。一旦您通过set_preference()
配置了所有设置,最后您必须使用update_preferences()
,如下所示:
self.profile.update_preferences()
参考文献
您可以在中找到一些相关的详细讨论
- Python AttributeError:通过Selenium和Python使用FirefoxProfile时,"FirefoxProfile"对象没有属性"update"错误
要解决此问题,需要包含路径&文件名为一个。
- 下面使用
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)