Python selenium open link in new tab

Open web in new tab Selenium + Python

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

Источник

Читайте также:  Java properties all keys

selenium new tab in chrome browser by python webdriver

I am not being able to open a new tab in chrome. My requirement is to open a new tab do some operation then close this new tab and come back to old tab. The below python code worked in Firefox but not working in Chrome. Could anyone please help me?

ActionChains(driver).key_down(Keys.CONTROL,body).send_keys('t').key_up(Keys.CONTROL).perform() 

This is working with Firefox . my requirement is to open a new tab not by clicking on any link on the 1st tab

2 Answers 2

Guess this will be helpful:

from selenium import webdriver driver = webdriver.Chrome() driver.execute_script("window.open('','_blank');") 

This piece of code should start new Chrome browser session and open blank page in new tab

Use driver.execute_script(«window.open(‘URL’);») to open new tab with required URL

I failed to open new tab with required URL by driver.execute_script(«window.open(‘URL’);») .

Therefore I changed my mind.

Any link will start on the new tab if we consider switching the current window to the new one. And I will open the new tab by driver.get(URL) . The only method I need to use is driver.switch_to_window(driver.window_handles[1]) .

We simply switch the window to the main window, when we close the new tab: driver.switch_to_window(driver.window_handles[0]) or driver.switch_to_window(main_window)

By the way, it will raise an error if we don’t switch to the main window after closing the new tab.

from selenium import webdriver driver = webdriver.Chrome() driver.get("http://www.google.com/") # save main_window main_window = driver.current_window_handle # obtain url of gmail on the home page of Google addr = driver.find_element_by_xpath('//*[@id="gbw"]/div/div/div[1]/div[1]/a').get_attribute("href") # open new blank tab driver.execute_script("window.open();") # switch to the new window which is second in window_handles array driver.switch_to_window(driver.window_handles[1]) # open successfully and close driver.get(addr) driver.close() # back to the main window driver.switch_to_window(main_window) driver.get(addr) 

Источник

lrhache / python-selenium-open-tab.md

On a recent project, I ran into an issue with Python Selenium webdriver. There’s no easy way to open a new tab, grab whatever you need and return to original window opener.

Here’s a couple people who ran into the same complication:

So, after many minutes (read about an hour) of searching, I decided to do find a quick solution to this problem.

First thing, I’ve broken down all the steps that were required to do by my program:

  1. Open a new window/tab by simulating a click on a link
  2. Add focus on this new tab
  3. Wait for an element on the new page to be rendered (ui.WebDriverWait)
  4. Do whatever I have to do on this new page
  5. Close the tab
  6. Return focus on original window opener
import selenium.webdriver as webdriver import selenium.webdriver.support.ui as ui from selenium.webdriver.common.keys import Keys from time import sleep 
browser = webdriver.Firefox() browser.get('https://www.google.com?q=python#q=python') first_result = ui.WebDriverWait(browser, 15).until(lambda browser: browser.find_element_by_class_name('rc')) first_link = first_result.find_element_by_tag_name('a') # Save the window opener (current window, do not mistaken with tab. not the same) main_window = browser.current_window_handle # Open the link in a new tab by sending key strokes on the element # 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 browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB) # Put focus on current window which will, in fact, put focus on the current visible tab browser.switch_to_window(main_window) # do whatever you have to do on this page, we will just got to sleep for now sleep(2) # Close current tab browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w') # Put focus on current window which will be the window opener browser.switch_to_window(main_window)

Источник

How To Switch Tabs In A Browser Using Selenium Python?

Join

This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Python Tutorial.

Selenium automation offers dexterous ways to perform day-to-day tasks most efficiently. From capturing screenshots to testing PDF files, there’s no limit to what you can do with Selenium automation. Developers and testers are masters of drilling websites and finding loopholes. More often than not, this drill involves switching tabs multiple times a day. To reduce the manual effort that goes into doing so, we recommend using Python Selenium to switch tabs.

In this article, we will help you master multiple ways to switch tabs in Selenium using Python. Let’s get started –

TABLE OF CONTENT

When Do We Need To Open Or Switch Tabs In Selenium Automation?

Opening a new tab or switching between multiple tabs is one of the most basic functions performed by all of us every single day. Let us look into some scenarios when opening or switching tabs comes in handy during Selenium automation.

App Suits – Testing Features That Can Work Parallely

The most obvious scenario is when your application is too big and has mini-applications within it. For example, if you have used Linkedin, you might have come across ‘Linkedin Learning’ & ‘Linkedin Sales Navigator’ as two sub-applications. Similarly, many other applications are composed of several other smaller constituent applications. For example, G-suite, Youtube (media player & creator studio), Hubspot, Azure & Amazon, etc., some of these, by default, open up in a new tab. For others, it makes sense to intentionally open a new application in a new tab. This is where Selenium automation testing comes in.

Testing Ecommerce App Features

Let’s take another example of e-commerce application testing. Suppose you are testing an e-commerce website and you want to add a product to the cart. Then, you want to check if it gets reflected on the cart page. Next, you want to add another product to the cart. And then you want to confirm if it is visible in the cart. Doing this in the same browser window and tab could be a tenacious & time-taking task, and that’s where Selenium automation comes in.

Multimedia Uploading Functionality Testing

Another common example could be of uploading multiple videos parallelly to a vlogging platform like Vimeo or Youtube. This is an ideal case for multi-browser, cross-tab testing.

In short, automation testing involves switching tabs in the following scenarios –

  • Testing parallel features of large applications. E.g., Zoho, G-suite, Office365, etc.
  • Testing links that automatically open in a new tab. E.g. – eCommerce applications
  • Parallel testing of independent applications if the need arises.

In this Python Selenium switch tabs tutorial, we will be focusing on opening and switching between the tabs using Python & Selenium. We have dedicated articles for on-page testing operations like handling alerts, drag and drop objects using a mouse, or taking full-page screenshots. You may want to refer to those to dive deeper into Selenium automation use cases.

This certification is for professionals looking to develop advanced, hands-on expertise in Selenium automation testing with Python and take their career to the next level.

Here’s a short glimpse of the Selenium Python 101 certification from LambdaTest:

How To Create A New Tab In Selenium Python?

In order to get started with Python Selenium switch tabs automation, your system needs to be equipped with the required tools. Here are all the prerequisites:

  • You have the latest Selenium-Python bindings, Python3, pip, virtualenv installed in your system
  • You also have a path to the executable WebDriver of your browser choice in your system.

If not, you can simply follow the instructions given in this Selenium 4 with Python blog to get started with Python Selenium switch tab automation. We can open new tabs in Selenium-Python by executing JavaScript as well as by using Selenium’s ActionChains class.

Let’s see how this can be done.

Open New Tabs In Selenium By Executing JavaScript

In the following code, replace “chrome_webdriver_executable_path” with the path to your chrome executable. Ideally, you should add it in your systems PATH variable.

Sample Code 1-

Источник

Оцените статью