Claude Bastien
Claude Bastien

Reputation: 141

How come I am getting InvalidSelectorException when trying to click a button using Selenium?

I am very new at working with Selenium. I am trying to click on the following Select button: enter image description here

Here is my code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FirstTest 
{
    private static WebDriver driver;

    public static void main(String[] args) throws Exception
    {
        driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.navigate().to("http://www.metro.ca/flyer/index.en.html");

        WebElement postalCodeInputBox = driver.findElement(By.name("postalcode"));
        postalCodeInputBox.sendKeys("L6R1A1");
        postalCodeInputBox.submit();

        String pageSource = driver.getPageSource();
        if(pageSource.contains("setstore btn"))
            System.out.println("setstore btn FOUND");

        WebElement selectButton = driver.findElement(By.className("setstore btn"));
        selectButton.click();
    }
}

Picture confirming that "setstore btn" is in the source: enter image description here

Here is "setstore btn" in the source: enter image description here

Upvotes: 0

Views: 129

Answers (1)

Parker Beck
Parker Beck

Reputation: 195

It's very likely caused by you trying to search for two separate classes in the single By.className(). "setstore" and "btn" are each their own classes.

Try replacing

WebElement selectButton = driver.findElement(By.className("setstore btn"));

with

WebElement selectButton = driver.findElement(new ByAll(By.className("setstore"), By.className("btn")));

Alternatively, https://stackoverflow.com/a/16090160/1055102 provides another good option.

WebElement selectButton = driver.findElement(By.cssSelector(".setstore.btn"));

Upvotes: 2

Related Questions