How to send shortcut keys in the current web browser?
Question: I am trying to send some shortcut keys to open a new tab in chrome, using
selenium in python. I open up facebook, then I log in, then I want to open a
new tab where I can pass the url of one of my friend so that I can view his
profile. I wrote the following code:

    
    
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    import getpass
    
    driver = webdriver.Chrome()
    
    #opening browser and loging into the account
    def login():
        driver.get("http://www.facebook.com")
        elem = driver.find_element_by_xpath("//*[@id=\"email\"]")
        elem.send_keys("myUsername")
        password = driver.find_element_by_name("pass")
        password.send_keys("myPassword")
        elem.send_keys(Keys.RETURN)
        driver.implicitly_wait(5)
    
    def scout():
        scroll =     driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
        driver.get("http://www.facebook.com/some.friend")
        driver.implicitly_wait(8)
    
    login()
    scout()
    

But it gives me the error:

    
    
    selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
    

I made the browser wait implicitly but still it's unable to find the tag.
Please help.


Answer: First of all, try calling `WebDriverWait` instead of
`find_element_by_css_selector` in order to find elements. It calls
`find_element_by_<method>` every half a second until given timeout. That way
you don't have to gamble with `implicitly_wait` or `time.sleep()`. Regarding
your open new tab problem - you cannot send ctrl + t to chromedriver, it
simply wouldn't do anything (it would work on firefox though). I've
encountered this problem before, and the best solution I found is to search
for a link in the website itself, so if you're on Facebook you can use that F
icon at the top left. Then you can send ctrl + shift + click to open that in a
new tab.

    
    
            from selenium.webdriver import ActionChains
            actions = ActionChains(driver);
            actions.move_to_element(link)
            actions.send_keys(Keys.CONTROL+ Keys.SHIFT)
            actions.click(link)
            actions.perform()
    

From there you should just switch tabs using

    
    
            tabs = driver.window_handles
            driver.switch_to.window(tabs[<index>])
    

