Exploring the Beauty of Selenium and Python by Navigating Links

On a webpage, there are multiple links displayed randomly. The code I've written is set to open the first link in a new tab and perform a function. However, I'm unsure how to handle this if there are more than one link. Is there a way to iterate through them or another method to address this issue?

The "Changerequest" link is available on the webpage.

Sourcecontrol = driver.find_element_by_xpath('//li[@class="menu-item"]/a[contains(.,"Source Control")]')
   Sourcecontrol.click();
   Changerequest=driver.find_element_by_xpath( '//td[@class="confluenceTd"]/a[contains(.,"Change: ")]');
   testvalue = Changerequest.get_attribute('href')
   driver.execute_script("window.open(arguments[0])",testvalue)
   window_after = driver.window_handles[1]
   driver.switch_to_window(window_after)

Here is a sample of the HTML for the links:

<div class="flooded">
                    <div class="table-wrap">
<table class="confluenceTable"><tbody>
<tr>
<td class="confluenceTd"><a href="link" class="external-link" rel="nofollow" title="Follow link">Change: 1111</a></td>
<td class="confluenceTd">date</td>
</tr>
<tr>
<td class="confluenceTd"><a href="Link" rel="nofollow" title="Follow link">Change: 2222</a></td>
<td class="confluenceTd">date</td>
</tr>
<tr>
<td class="confluenceTd"><a href="link" class="external-link" rel="nofollow" title="Follow link">Change: 33333</a></td>
<td class="confluenceTd">date</td>
</tr>
<tr>
<td class="confluenceTd"><a href="link" class="external-link" rel="nofollow" title="Follow link">Change: 44444</a></td>
<td class="confluenceTd">date</td>
</tr>
</tbody></table>
</div>

                </div>

Answer №1

Check out this code snippet.

import selenium
driver = webdriver.Chrome()
driver.get("url")
for item in driver.find_elements_by_css_selector('td.confluenceTd a'):
    link = item.get_attribute('href')
    window_before = driver.window_handles[0]
    driver.execute_script("window.open(arguments[0])",link)
    window_after = driver.window_handles[-1]
    driver.switch_to.window(window_after)
    #Perform specific action
    #
    print(driver.current_url)
    #
    driver.switch_to.window(window_before)

ALTERNATIVELY

for item in driver.find_elements_by_xpath("//td[@class='confluenceTd']//a[contains(.,'Change:')]"):
    link = item.get_attribute('href')
    window_before = driver.window_handles[0]
    driver.execute_script("window.open(arguments[0])",link)
    window_after = driver.window_handles[-1]
    driver.switch_to.window(window_after)
    #Perform specific action
    #
    print(driver.current_url)
    #
    driver.switch_to.window(window_before)

Answer №2

To gather all elements, utilize the find_elements function with s.

Your iteration should resemble the following:

for item in driver.find_elements_by_xpath( '//td[@class="confluenceTd"]/a'):
    value = item.get_attribute('href')
    driver.execute_script("window.open(arguments[0])",value)
    new_window = driver.window_handles[-1]
    driver.switch_to_window(new_window)
    # carry out desired actions...
    driver.switch_to.default_content()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Crisp, green cucumbers reveal their hidden value within

How can I extract the cucumber report values into variables within my code? For instance: int scenariosRun = cucumber.getScenarios(); // 8 int scenariosPassed = cucumber.getScenariosPassed(); // 8 https://i.stack.imgur.com/9M23U.png ...

Encountering a problem with Extent Reports where the error reads: 'The method attachReporter(ExtentSparkReporter) is not defined for the ExtentReports type'

Currently, I'm in the process of learning how to generate Extent Reports through tutorials on YouTube. As part of this learning journey, I am attempting to code the necessary steps. However, an error keeps popping up when I try to link SparkReports to ...

Utilizing C# Selenium to Extract Information from a Table Nested Within a Div

Currently, I am facing a challenge in extracting data from a table consisting of two columns where the rows lack a unique identifier. Despite this limitation, I can utilize the information in the first column to determine if I need to extract data from the ...

Error locating file /Users/sgantayat/Documents/Screenshots/Sikuli/Login.png at coordinates (756x124) within the screen resolution of 1680x1050

Encountering an error while executing the Sikuli code on a MacBook Pro. When calling the login method, the login screen appears. The ChromeDriver 100.0.4896.60 is started successfully on port 43572, with only local connections permitted. For security consi ...

Having trouble setting up the Selenium webdriver. Attempting to locate the most budget-friendly tickets. Any suggestions on how to achieve this

I am looking to create an app that can fetch the most affordable flight tickets from Skyscanner for specific destinations within a particular time frame. I have no issues with the request as Skyscanner retrieves all search data through Get. For instance: ...

Error encountered in Python when using Beautiful Soup for parsing

Every time I execute this code, an error pops up: soup = BeautifulSoup(sources, "lxml") TypeError: 'module' object is not callable from selenium import webdriver import bs4 as BeautifulSoup def html_pin(): browser = webdriver.Chrome() b ...

Having trouble extracting HTML output from a Selenium page when executing wdio.conf.js using the Selenium standalone service and Chrome browser

Upon running tests from wdio using the command 'wdio wdio.conf.js', an Error followed by html code of selenium page is being encountered. The package.json file contains the following configuration: { "name": "OpenWeathermap", "version": "1. ...

Combining JSON data within a MySQL column efficiently with the power of SQLAlchemy

Is there a way to consolidate JSON data that is spread out over multiple rows in a MySQL column using the Python SQLAlchemy library? I tried using json_merge_preserve but encountered difficulties applying it to an entire column. This was the code snippet ...

I want to transfer a static .html file from a Spring Boot application to an Angular application and display it within a specific component

Recently diving into the world of Angular and facing a challenge. I have a task where a .html report is created post executing selenium test cases in my backend, which happens to be a spring-boot application. My next step involves sending this .html repor ...

A guide on organizing a list in Python based on strings with the highest number of alphabetical characters

Suppose there is a list containing some strings. Can the list be sorted in such a way that the strings are arranged based on the alphabetical order of their characters if rearranged alphabetically? For example: ["tank", "ream", "ram", "banter"] would becom ...

Python/Selenium: Automating element selection when no id or class is available

My task is to automate clicking a button using Selenium. I have experimented with various find_elements_by...() methods and different arguments, but I am unable to determine the correct find_element_by*() method and its corresponding argument that needs t ...

Ways to incorporate my python script into a different file using visual studio code

I am currently using Python with Selenium in Visual Studio Code. My goal is to import another Python class called driverScript located within the executionEngine module, specifically in the file named DriverScript. I have attempted to import it as shown be ...

Having trouble identifying the elements within a Div pop-up in Chrome when executing Selenium automation

When automating on the website automationpractice.com, follow these steps: 1. Open "automationpractice.com/index.php?id_product=5&controller=product#/size-s/color-orange" 2. Click on the "Add to Cart" button 3. The successful "Add to Cart" pop-up will ...

Is there a function that includes a nested function within itself?

The heading may seem unusual, but I'm not entirely sure of the proper term to use in this context, so please bear with me and my vague title.... I came across some code online that looks like this: def lcs(xstr, ystr): """ >>> lcs( ...

Is it possible to use a Chrome flag to turn off progressive web apps (PWA) notifications during Selenium test executions?

I'm encountering issues with some web elements being blocked in mobile Selenium tests due to Chrome's PWA notification bar. Is there a solution to disable it? ...

When dealing with lengthy product names, Python Selenium may encounter difficulty retrieving the product's name

I need to extract information about all products (such as name, image, price, and link) from . However, I encountered a problem where the product card cannot display the full name of the product if it is too long, resulting in the name and price being retu ...

How to extract specific links with selenium in python

I am currently working on a project to extract links from news articles related to Apple from the following webpage: . However, I have encountered an issue where there are numerous advertisement links and other page redirections mixed in with the news arti ...

Guide on setting up the Firefox driver for Windows operating system

Is there a way to set up the firefox web driver for use with selenium\python? I went ahead and installed it using the following command: pip install selenium After that, I attempted running this code snippet: driver=webdriver.Firefox() driver.get(&q ...

Encountering difficulties when initializing AppiumDriver on Perfecto for Mobile Web Browser Testing

Our attempt to configure the instantiation of an Appium driver for Mobile Web Browser Testing on perfecto for Android and iOS is resulting in a "cannot be cast to class" error. The details are as follows: QAF Version Selenium - 4.11.0 Appium Java-Client ...

Element could not be located using the specified x-path

The HTML element code is: <html> < div class="view view-text" style="text-decoration: none; top: 9px; width: 216px; font-family: Kiro-webfont,Helvetica Neue,Arial; font-size: 20px; font-weight: bold; text-align: center; color: rgb(255, 255, 255) ...