Python - Selenium - How to use Browser Shortcuts

被刻印的时光 ゝ 提交于 2020-01-20 06:00:24

问题


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)

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

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




回答2:


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

ActionChains(browser).send_keys(Keys.CONTROL, "p").perform()

that would send the keyboard shortcut for a print dialog

I haven't found a way to do this in FF for printing though - ctrl+p will open the print dialog, but FF has a focus bug that doesn't allow one to do Keys.ENTER for the dialog itself

hopefully this will work for you in Chrome, I haven't tested it there

please update if you find a way around this - possibly try AutoIt

If none of the above works you can always do

browser.get_screenshot_as_file( path + 'page_image.jpg' )



回答3:


If i understood your question correctly my suggestion is that you install and use the pyautogui module to make your python program press keys

For example:

import pyautogui
pyautogui.hotkey('ctrl','p')

see the pyautogui documentation for more information: https://pyautogui.readthedocs.io/en/latest/introduction.html




回答4:


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)


来源:https://stackoverflow.com/questions/21905946/python-selenium-how-to-use-browser-shortcuts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!