Mitchell
Mitchell

Reputation: 1

Java Selenium - How to click on a button link element with no ID?

I've been trying to get the WebDriver to find the element by xpath and using the href link directly behind the button, however to no avail. Here's my code so far:

package mavensample;

import.java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class mavensample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "chromedriverpath";
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, Timeunit.SECONDS);
driver.manage().timeouts().implicitlyWait(40, Timeunit.SECONDS);
driver.get("https://initialLink.net/");
driver.findElement(By.cssSelector("a[href='https://censoredlink.net/']"));
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(“a[href=‘https://webqa.cenpos.net/vt/‘]”)));
}}

This is the elemnt info I get on inspect: a href= "https://censoredlink.net/" class="btn btn-sm btn-light mb-1" target="_blank">QA

I would normally locate the element through text, however there are multiple different QA buttons for different environments. I tried using CssSelector and just inputting the link directly however that didn't work either.

Any help is much appreciated!

Upvotes: 0

Views: 174

Answers (2)

Prophet
Prophet

Reputation: 33361

In case https://censoredlink.net/ is unique value for href attribute you can try the following XPath:

driver.findElement(By.xpath("//a[@href='https://censoredlink.net/']"))

Or with CssSelector

driver.findElement(By.cssSelector("a[href='https://censoredlink.net/']"))

UPD
I guess you are missing a wait. I mean you need to wait for the element to be loaded before accessing it. The best way to do that is to use WebDriverWait.
Also it's possible the element is inside iframe etc.
We need to see that page...

Upvotes: 0

KunduK
KunduK

Reputation: 33384

There is a typo error in your css selector. you need to remove ) this

Instead of this

driver.findElement(By.cssSelector("a[href='https://censoredlink.net/')]"));

It should have been

driver.findElement(By.cssSelector("a[href='https://censoredlink.net/']"));

Upvotes: 0

Related Questions