[Selenium] Open the link in a new tab and move it [Python / Chrome Driver]

Do you operate the browser?

Do you operate the same browser every day?

Let's leave such browser operation to Selenium!

Would you like to Ctrl + click a link to open it in a new tab while touching your browser? I do very well w

It will be such a series of flow.

Open and move the link in a new tab

sample.py



from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait

import platform

driver = webdriver.Chrome("chromedriver.exe") #chromedriver.exe load

#
#
#Processing up to the corresponding page
#
#

#Element to click
element = driver.find_element_by_xpath('/html/body/hogehoge')
#element = driver.find_element_by_link_text("hogehoge") #Click here if you want to get it with link text

#Handle list before clicking
handles_befor = driver.window_handles

#(Link)Open element in new tab
actions = ActionChains(driver)

if platform.system() == 'Darwin':
    #Command key because it is a Mac
    actions.key_down(Keys.COMMAND)
else:
    #Control key because it is not a Mac
    actions.key_down(Keys.CONTROL)

actions.click(element)
actions.perform()

#Wait up to 30 seconds for new tabs to open
WebDriverWait(driver, 30).until(lambda a: len(driver.window_handles) > len(handles_befor))

#Handle list after clicking
handles_after = driver.window_handles

#Handle list diff
handle_new = list(handles_after - sethandles_befor)

#Go to new tab
driver.switch_to.window(handle_new[0])

Be careful not to overload Let's put wait and sleep as appropriate.

Commentary

sample.py


from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait

Load the Selenium library and the packages you need this time.

sample.py


import platform

Load the library to determine the OS.

sample.py


driver = webdriver.Chrome("chromedriver.exe") #chromedriver.exe load

#
#
#Processing up to the corresponding page
#
#

Let's start the chrome driver and operate it.

sample.py


#Element to click
element = driver.find_element_by_xpath('/html/body/hogehoge')
#element = driver.find_element_by_link_text("hogehoge") #Click here if you want to get it with link text

Assign the element you click with xpath or link_text to a variable.

sample.py


#Handle list before clicking
handles_befor = driver.window_handles

Gets the handle in list format before the new tab opens.

sample.py


#(Link)Open element in new tab
actions = ActionChains(driver)

if platform.system() == 'Darwin':
    #Command key because it is a Mac
    actions.key_down(Keys.COMMAND)
else:
    #Control key because it is not a Mac
    actions.key_down(Keys.CONTROL)

actions.click(element)
actions.perform()

You can use a class called ʻActionChains` to record and execute keystrokes. On Mac and other operating systems, the shortcut key that opens in a new tab is different for the Google Chrome browser.

Mac: command + click Windows and Linux: Ctrl + click

The OS is judged by the platform library and conditional branching is performed.

ʻThe key operation recorded by actions.perform () `is executed.

sample.py


#Wait up to 30 seconds for new tabs to open
WebDriverWait(driver, 30).until(lambda a: len(driver.window_handles) > len(handles_befor))

It may take some time when a new tab opens, so let it wait. WebDriverWait (driver, 30)). until will allow the driver to wait up to 30 seconds.

In lambda a: len (driver.window_handles)> len (handles_befor), it is described in one line using a lambda expression.

len (handles_befor) than the number of handles before opening in a new tab len (driver.window_handles) The wait will be canceled when the number of handles exceeds the number of handles at the moment when a new tab is opened.

sample.py


#Handle list after clicking
handles_after = driver.window_handles

Gets the handle in list format after the new tab opens.

sample.py


#Handle list diff
handle_new = list(handles_after - handles_befor)

You can get the difference by subtracting the list with -. I'm assigning it to a variable.

sample.py


#Go to new tab
driver.switch_to.window(handle_new[0])

The difference handle_new [0] becomes the handle of the new tab, so move it with switch_to.window.

bonus

So that you can always go back if you open too many tabs and don't understand why (Let's not do that w)

It may be good to get the current handle in advance.

sample.py



#Current window(tab)Substitute the handle of
current_handle = driver.current_window_handle

#
#
#processing
#
#

#Current window(tab)Move to
driver.switch_to.window(current_handle)

Thank you very much!

Recommended Posts

[Selenium] Open the link in a new tab and move it [Python / Chrome Driver]
[Python / Jupyter] Translate the comment of the program copied to the clipboard and insert it in a new cell
[Python] How to save the installed package and install it in a new environment at once Mac environment
What to do if a version error occurs in the selenium Chrome driver
The result of making a map album of Italy honeymoon in Python and sharing it
Temporarily save a Python object and reuse it in another Python
[Selenium] Print without header and footer (forced) [Python / Chrome Driver]
Recursively get the Excel list in a specific folder with python and write it to Excel.
An easy way to view the time taken in Python and a smarter way to improve it
How to determine the existence of a selenium element in Python
New Python grammar and features not mentioned in the introductory book
Check and move directories in Python
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
Tips for using Selenium and Headless Chrome in a CUI environment
Selenium and python to open google
How to input a character string in Python and output it as it is or in the opposite direction.
Get a capture of the entire web page in Selenium Python VBA
When Selenium tells me that the Chrome driver version is different (Python)
Enclose the cat result in double quotes and put it in a variable
I set the environment variable with Docker and displayed it in Python
Open an Excel file in Python and color the map of Japan
Write the test in a python docstring
Run the Python interpreter in a script
Screenshots of Megalodon in selenium and Chrome.
Find it in the procession and edit it
Python open and io.open are the same
Create a Python image in Django without a dummy image file and test the image upload
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
Reinforcement learning 35 python Local development, paste a link to myModule and import it.
Make a Python program a daemon and run it automatically when the OS starts
Use libsixel to output Sixel in Python and output a Matplotlib graph to the terminal.
Note that I understand the least squares algorithm. And I wrote it in Python.
Create a Django project and application in a Python virtual environment and start the server
Define a division value in Django and easily reflect it on the screen
[Python] Automatically read prefectural information on the new coronavirus from the PDF of the Ministry of Health, Labor and Welfare and write it in a spreadsheet or Excel.
Organize python modules and packages in a mess
[Python] Get the files in a folder with Python
Try running Google Chrome with Python and Selenium
Get the caller of a function in Python
ffmpeg-Build a python environment and split the video
I wrote a class in Python3 and Java
About the difference between "==" and "is" in python
Let's write a Python program and run it
Create a new page in confluence with Python
Output in the form of a python array
POST JSON in Python and receive it in PHP
[Python] Find the transposed matrix in a comprehension
A discussion of the strengths and weaknesses of Python
A Python script that crawls RSS in Azure Status and posts it to Hipchat
If you define a method in a Ruby class and define a method in it, it becomes a method of the original class.
Automate background removal for the latest portraits in a directory with Python and API
Draw a weakness graph in Python and save it in various formats (Raspberry Pi, macOS)
[Python3] Take a screenshot of a web page on the server and crop it further
Selenium-Screenshot is useful for screenshots of web pages in Python3, Selenium and Google Chrome
Get information equivalent to the Network tab of Chrome developer tools with Python + Selenium
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
I want to replace the variables in the python template file and mass-produce it in another file.
Open page in secret mode by specifying browser language with Selenium Python Bindings (Chrome)
It seems that a new lottery with a total score will start in the sports lottery,
[Mac] A super-easy way to execute system commands in Python and output the results
A note that runs an external program in Python and parses the resulting line