Python - Selenium - 如何使用浏览器快捷方式

Pho*_*nix 6 python browser printing selenium python-3.x

加载浏览器页面后,我希望使用Goggle Chrome中的CRTL + P快捷键进入打印页面,然后只需按返回即可打印页面.

import time
from selenium import webdriver

# Initialise the webdriver
chromeOps=webdriver.ChromeOptions()
chromeOps._binary_location = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
chromeOps._arguments = ["--enable-internal-flash"]
browser = webdriver.Chrome("C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe", port=4445, chrome_options=chromeOps)
time.sleep(3)

# Login to Webpage
browser.get('www.webpage.com')
Run Code Online (Sandbox Code Playgroud)

我的问题是如何将密钥发送到浏览器本身而不是元​​素?

尝试失败:将html主体指定为元素并将密钥发送给 -

elem = browser.find_element_by_xpath("/html/body") # href link
elem.send_keys(Keys.CONTROL + "P")      # Will open a second tab
time.sleep(3)
elem.send_keys(Keys.RETURN)
Run Code Online (Sandbox Code Playgroud)

use*_*679 0

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

ActionChains(browser).send_keys(Keys.CONTROL, "p").perform()
Run Code Online (Sandbox Code Playgroud)

这将发送打印对话框的键盘快捷键

我还没有找到一种方法可以在 FF 中执行此操作以进行打印 - ctrl+p 将打开打印对话框,但 FF 有一个焦点错误,不允许对对话框本身执行 Keys.ENTER

希望这对你在 Chrome 中有用,我还没有在那里测试过

如果您找到解决方法,请更新 - 可以尝试 AutoIt

如果以上方法都不起作用,你可以随时这样做

browser.get_screenshot_as_file( path + 'page_image.jpg' )
Run Code Online (Sandbox Code Playgroud)