Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Selenium - How to use Browser Shortcuts

Once a browser page is loaded I'm looking to use the CRTL+P shortcut in Goggle Chrome to enter the print page and then simply press return to print the page.

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')

My question is how do I send keys to the browser itself rather than an element?

Failed Attempt: To assign the html body to as the element and send keys to that-

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)
like image 651
Phoenix Avatar asked Feb 20 '14 11:02

Phoenix


2 Answers

I have tested this on Google Chrome and the problem can be solved using a combination of .key_down() and .send_keys() methods of the ActionChains class.

ActionChains(driver).key_down(Keys.CONTROL).send_keys('p').key_up(Keys.CONTROL).perform()
ActionChains(driver).send_keys(Keys.ENTER)
like image 85
GPT14 Avatar answered Oct 29 '22 16:10

GPT14


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')

Just a note, this will open Firefox print panel. But the same code will not work in Goggle Chrome.

like image 28
Phoenix Avatar answered Oct 29 '22 16:10

Phoenix