加载浏览器页面后,我希望使用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')
我的问题是如何将密钥发送到浏览器本身而不是元素?
尝试失败:将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)
答案 0 :(得分:1)
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser.get('https://www.myglenigan.com/project_search_results.aspx?searchId='+ID)
element=browser.find_element_by_xpath("//body")
element.send_keys(Keys.CONTROL, 'p')
只需注意,这将打开Firefox打印面板。但是相同的代码在Goggle Chrome中无效。
答案 1 :(得分:1)
如果我理解你的问题我的建议是你安装并使用pyautogui模块让你的python程序按键
例如:
import pyautogui
pyautogui.hotkey('ctrl','p')
有关更多信息,请参阅pyautogui文档: https://pyautogui.readthedocs.io/en/latest/introduction.html
答案 2 :(得分:0)
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
ActionChains(browser).send_keys(Keys.CONTROL, "p").perform()
将发送打印对话框的键盘快捷键
我还没有找到在FF中进行打印的方法 - ctrl + p将打开打印对话框,但FF有一个焦点错误,不允许人们为对话框本身做Keys.ENTER < / p>
希望这对你在Chrome中有用,我还没有在那里测试
如果您找到解决方法,请更新 - 可能尝试AutoIt
如果以上都不起作用,您可以随时
browser.get_screenshot_as_file( path + 'page_image.jpg' )
答案 3 :(得分:0)
我在Google Chrome上对此进行了测试,可以使用ActionChains类的.key_down()
和.send_keys()
方法组合解决问题。
ActionChains(driver).key_down(Keys.CONTROL).send_keys('p').key_up(Keys.CONTROL).perform()
ActionChains(driver).send_keys(Keys.ENTER)