Send keys control + click in Selenium with Python bindings - python

I need to open link in new tab using Selenium.
So is it possible to perform ctrl+click on element in Selenium to open it in new tab?

Use an ActionChain with key_down to press the control key, and key_up to release it:
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('http://google.com')
element = driver.find_element_by_link_text('About')
ActionChains(driver) \
.key_down(Keys.CONTROL) \
.click(element) \
.key_up(Keys.CONTROL) \
.perform()
time.sleep(10) # Pause to allow you to inspect the browser.
driver.quit()

Two possible solutions:
opening a new tab
self.driver = webdriver.Firefox()
self.driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
this is the solution for MAC OSX. In other cases you can use the standard Keys.CONTROL + 't'
opening a new webdriver
driver = webdriver.Firefox() #1st window
second_driver = webdriver.Firefox() #2nd windows

Below is what i have tried for Selenium WebDriver with Java binding and its working for me.
If you want to manually open the Link in New Tab you can achieve this by performing Context Click on the Link and selecting 'Open in new Tab' option. Below is the implementation in Selenium web-driver with Java binding.
Actions newTab= new Actions(driver);
WebElement link = driver.findElement(By.xpath("//xpath of the element"));
//Open the link in new window
newTab.contextClick(link).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
Web-driver handles new tab in the same way to that of new window. You will have to switch to new open tab by its window name.
driver.switchTo().window(windowName);
You can keep track of window-names which will help you to easily navigate between tabs.

By importing Keys Class, we can open page in new tab or new window with CONTROL or SHIFT and ENTER these keys:
driver.find_element_by_xpath('//input[#name="login"]').send_keys(Keys.CONTROL,Keys.ENTER)
or
driver.find_element_by_xpath('//input[#name="login"]').send_keys(Keys.SHIFT,Keys.ENTER)

For python, a good solution would be driver.find_element_by_css_selector('<enter css selector here>').send_keys(Keys.CONTROL, Keys.RETURN)
After that, you should change windows so selenium could function in the new window
window_before = driver.window_handles[0]
window_after = driver.window_handles[1]
driver.switch_to_window(window_after)
After using the window is useful to close it or go back to the original:
Close tab: driver.close()
Back to the original: driver.switch_to_window(window_before)
Also try driver.switch_to.window() if your Selenium version does not support the other one

Following is working for me to open link in new tab :
String link = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.linkText("yourlinktext")).sendKeys(link);
Above code is in java. you can convert to python easily I assume.
Please ask if have any query.

Related

CTRL + CLick or CTRL + Enter not working its desiable by javascript cant open new tab [duplicate]

There is a link embedded in a web element in the Main Tab, I want to open that link in a new tab in the same window using Selenium Webdriver and python.
Perform some tasks in the new tab and then close that tab and return back to the main tab.
Manually we will do this by right-clicking on the link and then select "open in new tab" to open that link in new tab.
I am new to Selenium. I am using Selenium and BeautifulSoup to web scrape. I only know how to click on a link. I have read through many posts but couldn't find a proper answer
url = "https://www.website.com"
path = r'path_to_chrome_driver'
drive = webdriver.Chrome(path)
drive.implicitly_wait(30)
drive.get(url)
source = drie.page_source
py_button = driver.find_element_by_css_selector("div[data-res-position = '1']")
py_button.click()
I expect the link in div[data-res-position = '1'] to open in a new tab
As there is a link embedded within in the webelement in the Parent Tab, to open the link in a New Tab in the same window using Selenium and Python you can use the following solution:
To demonstrate the workflow the url https://www.google.com/ was opened in the Parent Tab and then open in new tab functionalty is implemented through ActionChains methods key_down(), click() and key_up() methods.
Code Block:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
driver = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get("https://www.google.com/")
link = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Gmail")))
ActionChains(driver).key_down(Keys.CONTROL).click(link).key_up(Keys.CONTROL).perform()
Note: You need to replace (By.LINK_TEXT, "Gmail") with your desired locator e.g. ("div[data-res-position = '1']")
Browser Snapshot:
You can find a relevant Java based solution in Opening a new tab using Ctrl + click combination in Selenium Webdriver
Update
To shift Selenium's focus to the newly opened tab you can find a detailed discussion in Open web in new tab Selenium + Python
This is trick can be achieve if your locator return a correct href.
Try this first:
href = driver.find_element_by_css_selector("div[data-res-position = '1']").get_attribute("href")
print(href)
If you get correct href, you can do:
#handle current tab
first_tab = driver.window_handles[0]
#open new tab with specific url
driver.execute_script("window.open('" +href +"');")
#hadle new tab
second_tab = driver.window_handles[1]
#switch to second tab
driver.switch_to.window(second_tab)
#switch to first tab
driver.switch_to.window(first_tab)
Hope this helps.
Following import:
selenium.webdriver.common.keys import Keys
You have to send key:
py_button.send_keys(Keys.CONTROL + 't')

How do I open/close tabs with Selenium (Python)?

I have tried all the methods in similar questions and only one of them worked which was to use javascript.
driver.execute_script("window.open('')")
#this works
ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
#this doesn't
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
#this doesn't work either
I'd like to get the second way to work, since it seems the most readable and sensible, am I doing something wrong in my code? Or is there any option I need to change in Selenium to enable opening tabs like this?
Edit: The 2nd and 3rd method don't produce any result at all. Not even an exception.
Below code works for me for opening and closing tabs:
import time
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.python.org")
time.sleep(2)
# open new tab
driver.execute_script("window.open('');")
# switch to the new tab and open new URL there
driver.switch_to.window(driver.window_handles[1])
driver.get("http://www.python.org")
time.sleep(2)
chld = driver.window_handles[1]
driver.switch_to.window(chld)
driver.close()
The second way didn't work for me as well.
import the selenium module
from selenium import webdriver
creates selenium object
driver = webdriver.Chrome()
gets the url needed for the driver object
url = "https://www.google.com/"
Open a new window
driver.execute_script("window.open('');")
Close the tab
driver.close()

Selenium webdriver closes unexpectedly with terminal [duplicate]

So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed...
I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this:
Open Browser
Loop throught my array
For element in array -> Open website in new tab -> do my business -> close it
But I can't find any way to achieve this.
Here's the code I'm using. It takes forever between websites, I need it to be fast... Other tools are allowed, but I don't know too many tools for scrapping website content that loads with JavaScript (divs created when some event is triggered on load etc) That's why I need Selenium... BeautifulSoup can't be used for some of my pages.
#!/usr/bin/env python
import multiprocessing, time, pika, json, traceback, logging, sys, os, itertools, urllib, urllib2, cStringIO, mysql.connector, shutil, hashlib, socket, urllib2, re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from PIL import Image
from os import listdir
from os.path import isfile, join
from bs4 import BeautifulSoup
from pprint import pprint
def getPhantomData(parameters):
try:
# We create WebDriver
browser = webdriver.Firefox()
# Navigate to URL
browser.get(parameters['target_url'])
# Find all links by Selector
links = browser.find_elements_by_css_selector(parameters['selector'])
result = []
for link in links:
# Extract link attribute and append to our list
result.append(link.get_attribute(parameters['attribute']))
browser.close()
browser.quit()
return json.dumps({'data': result})
except Exception, err:
browser.close()
browser.quit()
print err
def callback(ch, method, properties, body):
parameters = json.loads(body)
message = getPhantomData(parameters)
if message['data']:
ch.basic_ack(delivery_tag=method.delivery_tag)
else:
ch.basic_reject(delivery_tag=method.delivery_tag, requeue=True)
def consume():
credentials = pika.PlainCredentials('invitado', 'invitado')
rabbit = pika.ConnectionParameters('localhost',5672,'/',credentials)
connection = pika.BlockingConnection(rabbit)
channel = connection.channel()
# Conectamos al canal
channel.queue_declare(queue='com.stuff.images', durable=True)
channel.basic_consume(callback,queue='com.stuff.images')
print ' [*] Waiting for messages. To exit press CTRL^C'
try:
channel.start_consuming()
except KeyboardInterrupt:
pass
workers = 5
pool = multiprocessing.Pool(processes=workers)
for i in xrange(0, workers):
pool.apply_async(consume)
try:
while True:
continue
except KeyboardInterrupt:
print ' [*] Exiting...'
pool.terminate()
pool.join()
Editor's note: This answer no longer works for new Selenium versions. Refer to this comment.
You can achieve the opening/closing of a tab by the combination of keys COMMAND + T or COMMAND + W (OSX). On other OSs you can use CONTROL + T / CONTROL + W.
In selenium you can emulate such behavior.
You will need to create one webdriver and as many tabs as the tests you need.
Here it is the code.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://www.google.com/")
#open tab
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
# You can use (Keys.CONTROL + 't') on other OSs
# Load a page
driver.get('http://stackoverflow.com/')
# Make the tests...
# close the tab
# (Keys.CONTROL + 'w') on other OSs.
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'w')
driver.close()
browser.execute_script('''window.open("http://bings.com","_blank");''')
Where browser is the webDriver
This is a common code adapted from another examples:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://www.google.com/")
#open tab
# ... take the code from the options below
# Load a page
driver.get('http://bings.com')
# Make the tests...
# close the tab
driver.quit()
the possible ways were:
Sending <CTRL> + <T> to one element
#open tab
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
Sending <CTRL> + <T> via Action chains
ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
Execute a javascript snippet
driver.execute_script('''window.open("http://bings.com","_blank");''')
In order to achieve this you need to ensure that the preferences browser.link.open_newwindow and browser.link.open_newwindow.restriction are properly set. The default values in the last versions are ok, otherwise you supposedly need:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.link.open_newwindow", 3)
fp.set_preference("browser.link.open_newwindow.restriction", 2)
driver = webdriver.Firefox(browser_profile=fp)
the problem is that those preferences preset to other values and are frozen at least selenium 3.4.0. When you use the profile to set them with the java binding there comes an exception and with the python binding the new values are ignored.
In Java there is a way to set those preferences without specifying a profile object when talking to geckodriver, but it seem to be not implemented yet in the python binding:
FirefoxOptions options = new FirefoxOptions().setProfile(fp);
options.addPreference("browser.link.open_newwindow", 3);
options.addPreference("browser.link.open_newwindow.restriction", 2);
FirefoxDriver driver = new FirefoxDriver(options);
The third option did stop working for python in selenium 3.4.0.
The first two options also did seem to stop working in selenium 3.4.0. They do depend on sending CTRL key event to an element. At first glance it seem that is a problem of the CTRL key, but it is failing because of the new multiprocess feature of Firefox. It might be that this new architecture impose new ways of doing that, or maybe is a temporary implementation problem. Anyway we can disable it via:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.tabs.remote.autostart", False)
fp.set_preference("browser.tabs.remote.autostart.1", False)
fp.set_preference("browser.tabs.remote.autostart.2", False)
driver = webdriver.Firefox(browser_profile=fp)
... and then you can use successfully the first way.
OS: Win 10,
Python 3.8.1
selenium==3.141.0
from selenium import webdriver
import time
driver = webdriver.Firefox(executable_path=r'TO\Your\Path\geckodriver.exe')
driver.get('https://www.google.com/')
# Open a new window
driver.execute_script("window.open('');")
# Switch to the new window
driver.switch_to.window(driver.window_handles[1])
driver.get("http://stackoverflow.com")
time.sleep(3)
# Open a new window
driver.execute_script("window.open('');")
# Switch to the new window
driver.switch_to.window(driver.window_handles[2])
driver.get("https://www.reddit.com/")
time.sleep(3)
# close the active tab
driver.close()
time.sleep(3)
# Switch back to the first tab
driver.switch_to.window(driver.window_handles[0])
driver.get("https://bing.com")
time.sleep(3)
# Close the only tab, will also close the browser.
driver.close()
Reference: Need Help Opening A New Tab in Selenium
The other solutions do not work for chrome driver v83.
Instead, it works as follows, suppose there is only 1 opening tab:
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
driver.get("https://www.example.com")
If there are already more than 1 opening tabs, you should first get the index of the last newly-created tab and switch to the tab before calling the url (Credit to tylerl) :
driver.execute_script("window.open('');")
driver.switch_to.window(len(driver.window_handles)-1)
driver.get("https://www.example.com")
In a discussion, Simon clearly mentioned that:
While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.
Using Selenium v3.x opening a website in a New Tab through Python is much easier now. We have to induce an WebDriverWait for number_of_windows_to_be(2) and then collect the window handles every time we open a new tab/window and finally iterate through the window handles and switchTo().window(newly_opened) as required. Here is a solution where you can open http://www.google.co.in in the initial TAB and https://www.yahoo.com in the adjacent TAB:
Code Block:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("http://www.google.co.in")
print("Initial Page Title is : %s" %driver.title)
windows_before = driver.current_window_handle
print("First Window Handle is : %s" %windows_before)
driver.execute_script("window.open('https://www.yahoo.com')")
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
windows_after = driver.window_handles
new_window = [x for x in windows_after if x != windows_before][0]
driver.switch_to.window(new_window)
print("Page Title after Tab Switching is : %s" %driver.title)
print("Second Window Handle is : %s" %new_window)
Console Output:
Initial Page Title is : Google
First Window Handle is : CDwindow-B2B3DE3A222B3DA5237840FA574AF780
Page Title after Tab Switching is : Yahoo
Second Window Handle is : CDwindow-D7DA7666A0008ED91991C623105A2EC4
Browser Snapshot:
Outro
You can find the java based discussion in Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium
Try this it will work:
# Open a new Tab
driver.execute_script("window.open('');")
# Switch to the new window and open URL B
driver.switch_to.window(driver.window_handles[1])
driver.get(tab_url)
After struggling for so long the below method worked for me:
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
windows = driver.window_handles
time.sleep(3)
driver.switch_to.window(windows[1])
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get('https://www.google.com')
driver.execute_script("window.open('');")
time.sleep(5)
driver.switch_to.window(driver.window_handles[1])
driver.get("https://facebook.com")
time.sleep(5)
driver.close()
time.sleep(5)
driver.switch_to.window(driver.window_handles[0])
driver.get("https://www.yahoo.com")
time.sleep(5)
#driver.close()
https://www.edureka.co/community/52772/close-active-current-without-closing-browser-selenium-python
just for future reference, the simple way could be done as this:
driver.switch_to.new_window()
t=driver.window_handles[-1]# Get the handle of new tab
driver.switch_to.window(t)
driver.get(target_url) # Now the target url is opened in new tab
The 4.0.0 version of Selenium supports the following operations:
to open a new tab try:
driver.switch_to.new_window()
to switch to a specific tab (note that the tabID starts from 0):
driver.switch_to.window(driver.window_handles[tabID])
Strangely, so many answers, and all of them are using surrogates like JS and keyboard shortcuts instead of just using a selenium feature:
def newTab(driver, url="about:blank"):
wnd = driver.execute(selenium.webdriver.common.action_chains.Command.NEW_WINDOW)
handle = wnd["value"]["handle"]
driver.switch_to.window(handle)
driver.get(url) # changes the handle
return driver.current_window_handle
I'd stick to ActionChains for this.
Here's a function which opens a new tab and switches to that tab:
import time
from selenium.webdriver.common.action_chains import ActionChains
def open_in_new_tab(driver, element, switch_to_new_tab=True):
base_handle = driver.current_window_handle
# Do some actions
ActionChains(driver) \
.move_to_element(element) \
.key_down(Keys.COMMAND) \
.click() \
.key_up(Keys.COMMAND) \
.perform()
# Should you switch to the new tab?
if switch_to_new_tab:
new_handle = [x for x in driver.window_handles if x!=base_handle]
assert len new_handle == 1 # assume you are only opening one tab at a time
# Switch to the new window
driver.switch_to.window(new_handle[0])
# I like to wait after switching to a new tab for the content to load
# Do that either with time.sleep() or with WebDriverWait until a basic
# element of the page appears (such as "body") -- reference for this is
# provided below
time.sleep(0.5)
# NOTE: if you choose to switch to the window/tab, be sure to close
# the newly opened window/tab after using it and that you switch back
# to the original "base_handle" --> otherwise, you'll experience many
# errors and a painful debugging experience...
Here's how you would apply that function:
# Remember your starting handle
base_handle = driver.current_window_handle
# Say we have a list of elements and each is a link:
links = driver.find_elements_by_css_selector('a[href]')
# Loop through the links and open each one in a new tab
for link in links:
open_in_new_tab(driver, link, True)
# Do something on this new page
print(driver.current_url)
# Once you're finished, close this tab and switch back to the original one
driver.close()
driver.switch_to.window(base_handle)
# You're ready to continue to the next item in your loop
Here's how you could wait until the page is loaded.
you can use this to open a new tab
driver.execute_script("window.open('http://google.com', 'new_window')")
This worked for me:-
link = "https://www.google.com/"
driver.execute_script('''window.open("about:blank");''') # Opening a blank new tab
driver.switch_to.window(driver.window_handles[1]) # Switching to newly opend tab
driver.get(link)
just enough use this to open new window(for example):
driver.find_element_by_link_text("Images").send_keys(Keys.CONTROL + Keys.RETURN)
I tried for a very long time to duplicate tabs in Chrome running using action_keys and send_keys on body. The only thing that worked for me was an answer here. This is what my duplicate tabs def ended up looking like, probably not the best but it works fine for me.
def duplicate_tabs(number, chromewebdriver):
#Once on the page we want to open a bunch of tabs
url = chromewebdriver.current_url
for i in range(number):
print('opened tab: '+str(i))
chromewebdriver.execute_script("window.open('"+url+"', 'new_window"+str(i)+"')")
It basically runs some java from inside of python, it's incredibly useful. Hope this helps somebody.
Note: I am using Ubuntu, it shouldn't make a difference but if it doesn't work for you this could be the reason.
Opening the new empty tab within same window in chrome browser is not possible up to my knowledge but you can open the new tab with web-link.
So far I surfed net and I got good working content on this question.
Please try to follow the steps without missing.
import selenium.webdriver as webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('https://www.google.com?q=python#q=python')
first_link = driver.find_element_by_class_name('l')
# Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack
first_link.send_keys(Keys.CONTROL + Keys.RETURN)
# Switch tab to the new tab, which we will assume is the next one on the right
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
driver.quit()
I think this is better solution so far.
Credits: https://gist.github.com/lrhache/7686903
tabs = {}
def new_tab():
global browser
hpos = browser.window_handles.index(browser.current_window_handle)
browser.execute_script("window.open('');")
browser.switch_to.window(browser.window_handles[hpos + 1])
return(browser.current_window_handle)
def switch_tab(name):
global tabs
global browser
if not name in tabs.keys():
tabs[name] = {'window_handle': new_tab(), 'url': url+name}
browser.get(tabs[name]['url'])
else:
browser.switch_to.window(tabs[name]['window_handle'])
As already mentioned several times, the following approaches are NOT working anymore:
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
Moreover, driver.execute_script("window.open('');") is working but is limited by the popup blocker. I process hundreds of tabs in parallel (web scraping using scrapy). However, the popup blocker became active after opening 20 new tabs using JavaScript's window.open('') and, thus, has broke my crawler.
As work around I declared a tab as "master" which has opended the following helper.html:
<!DOCTYPE html>
<html><body>
<a id="open_new_window" href="about:blank" target="_blank">open a new window</a>
</body></html>
Now, my (simplified) crawler can open as many tabs as necessary by purposely clicking the link which is not considered by the popup blogger at all:
# master
master_handle = driver.current_window_handle
helper = os.path.join(os.path.dirname(os.path.abspath(__file__)), "helper.html")
driver.get(helper)
# open new tabs
for _ in range(100):
window_handle = driver.window_handles # current state
driver.switch_to_window(master_handle)
driver.find_element_by_id("open_new_window").click()
window_handle = set(driver.window_handles).difference(window_handle).pop()
print("new window handle:", window_handle)
Closing these windows via JavaScript's window.close() is no problem.
#Change the method of finding the element if needed
self.find_element_by_xpath(element).send_keys(Keys.CONTROL + Keys.ENTER)
This will find the element and open it in a new tab. self is just the name used for the webdriver object.

How to duplicate the tab using selenium and python?

I use chrome as my web-driver and I want to duplicate the tab as the following picture shows (action: click the right button on the tab and choose "duplicate"). In this way, the words I typed in the previous page will retain in the duplicated page. And it seems that I can't do it with opening the tab with the same URL (the words will disappear). Can someone tell me how to do it with selenium? Thanks very much!
https://drive.google.com/file/d/1bTbrtnT78xP3bHfQvt8xiVEIETwKWHvz/view?usp=sharing
If you are using chrome you can try to use ActionChains to open duplicate tab by key shortcut
alt + d, enter
action_chains = ActionChains(driver)
action_chains.key_down(Keys.ALT).send_keys('d').perform()
action_chains.key_down(Keys.ENTER).perform()
action_chains.key_up(Keys.ALT).key_up(Keys.ENTER).perform()
If you are using chrome as the web driver, you can try to use selenium to add the extension "Duplicate tab shortcut" first:
chromedriver = "chromedriver.exe"
chrome_options = Options()
chrome_options.add_extension('Path\to\the\crx\file')
driver = webdriver.Chrome(executable_path=chromedriver, chrome_options=chrome_options)
And use ActionChains to duplicate the tab:
action_chains = ActionChains(driver)
action_chains.key_down(Keys.ALT).key_down(Keys.SHIFT).send_keys('d').perform()
action_chains.key_up(Keys.ALT).key_up(Keys.SHIFT).perform()
In this way you can duplicate the tab and keep its history.

How to perform right click using Selenium ChromeDriver?

I have been searching for this a lot, but could not find an answer for Python.
Is it possible to simulate right click, or open up the context menu via selenium/chromedriver?
I have seen options for Java, and some other languages, but never in Python.
What would I have to do to simulate a right click on a link, or a picture?
It's called context_click in selenium.webdriver.common.action_chains. Note that Selenium can't do anything about browser level context menu, so I assume your link will pop up HTML context menu.
from selenium import webdriver
from selenium.webdriver import ActionChains
driver = webdriver.Chrome()
actionChains = ActionChains(driver)
actionChains.context_click(your_link).perform()
To move through the context menu we have to use pyautogui along with selenium. The reason for using pyautogui is that we need to have control of the mouse for controlling the options on the context menu. To demonstrate this, I am going to use a python code to automatically open a google image of Avengers Endgame in new tab.
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import pyautogui
URL = 'https://www.google.com/'
PATH = r'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
action = ActionChains(driver)
driver.get(URL)
search = driver.find_element_by_name('q')
search.send_keys('Avengers Endgame')
search.send_keys(Keys.RETURN)
image_tab = driver.find_element_by_xpath('//a[text()="Images"]')
image_tab.click()
required_image = driver.find_element_by_xpath('//a[#class="wXeWr islib nfEiy mM5pbd"]')
action.context_click(required_image).perform()
pyautogui.moveTo(120, 130, duration=1)
pyautogui.leftClick()
time.sleep(1)
pyautogui.moveTo(300,40)
pyautogui.leftClick()
Now in the above code, the part till pyautogui.moveTo(120, 130, duration=1) is selenium based. Your answer begins from pyautogui.moveTo(120, 130, duration=1) and what this does is simply moves the mouse button to the open image in new tab option of the context menu(Please note that the screen coordinates may vary based on your screen size). The next line clicks the option(using action.click().perform() won't work as expected).
The next two lines helps in navigating to the tab after it opens. Hope the code helps!
I encountered the same issue where I had to right-click and click on 'open link in new tab'.
I searched for a lot of answers on google but there was no specific solution I found for Python.
Earlier, I was doing using ActionChains where right-click menu is showing, but then that menu list can't be accessed in selenium as I found some threads saying this has OS-level access.
action = ActionChains(driver)
action.context_click(<obj_which_u_want_to_click>).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ENTER).perform()
Here, Keys.ARROW_DOWN is not working, and opening the link in the same tab, ideally, it should open in a new tab.
So, there are two ways through which I did this:
First, via send_keys:
link = driver.find_elements_by_xpath("//a[contains(#href, 'https:...')]")
link.send_keys(Keys.CONTROL + Keys.ENTER)
Second, through JavaScript:
driver.execute_script("window.open(arguments[0], '_blank');", link)
I think you can't access the right-click menu items in selenium as it is out of its scope.
You can perform context click using ActionChains, and use Arrows via send_keys to select an element from the context menu.
ActionChains(context.browser).move_to_element(element).context_click(element).perform()
ActionChains(context.browser).send_keys(Keys.ARROW_UP).perform()
ActionChains(context.browser).send_keys(Keys.ENTER).perform()

Categories

Resources