如何通过selenium使用浏览器功能?

weixin_46129709 2021-03-25 01:59:42
举个例子,像下图这样浏览器自带的将网页打印为pdf文件之类的操作

可以在脚本中唤起该弹出的打印页面吗?或者在脚本中调用这项功能而不打开这个打印页面也是可以的
主要原因就在于所需要的pdf文件内容有格式要求,要求和浏览器ctrl+p进行打印导出的pdf格式相同,所以不能单纯用selenium自带的网页截图方法。
...全文
149 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_46129709 2021-03-29
  • 打赏
  • 举报
回复
引用 2 楼 考古学家lx的回复:
方法1、使用 Wkhtmltopdf工具包可以直接把html转为pdf 方法2、使用selenium保存pdf

import json
from selenium import webdriver
driver = webdriver.Chrome()
resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
url = driver.command_executor._url + resource
body = json.dumps({'cmd': 'Page.printToPDF', 'params':  {
            'landscape': False,
            'displayHeaderFooter': False,
            'printBackground': True,
            'preferCSSPageSize': True,
        }})
response = driver.command_executor._request('POST', url, body)
result = response.get('value')
with open('report.pdf', 'wb') as file:
    file.write(result)
最终采用了方法2,多谢老哥
  • 打赏
  • 举报
回复
方法1、使用 Wkhtmltopdf工具包可以直接把html转为pdf 方法2、使用selenium保存pdf

import json
from selenium import webdriver
driver = webdriver.Chrome()
resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
url = driver.command_executor._url + resource
body = json.dumps({'cmd': 'Page.printToPDF', 'params':  {
            'landscape': False,
            'displayHeaderFooter': False,
            'printBackground': True,
            'preferCSSPageSize': True,
        }})
response = driver.command_executor._request('POST', url, body)
result = response.get('value')
with open('report.pdf', 'wb') as file:
    file.write(result)
weiweixiao995 2021-03-25
  • 打赏
  • 举报
回复
不知道selenium能不能直接唤起打印页面,但是你可以在需要打印的时候自动输入CTRL+p快捷键 就可以了。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import pyautogui
from selenium import webdriver


re = webdriver.Chrome()
re.get('https://www.baidu.com')
pyautogui.hotkey('ctrl', 'p')
time.sleep(2)
re.quit()

37,744

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧