How to access WebElement by XPath by Selenium?

I need to access links to result of search on this website (https://www.pibr.org.pl/pl/search/auditor?biegli=1&firmy=1&name=&post_code=&city=Warszawa) and put them in WebElement, but I cant locate them by class or anything. While using xpath:

MyWebDriver.findElement(By.xpath("//div[@class=inner-results firma]")).click();

I get this error:

"Given xpath expression "//div[@class=inner-results firma]" is invalid: SyntaxError: The expression is not a legal expression."

How can I access all result links?

Upvotes: 2

Views: 733

Answers (3)

Bhavesh Soni
Bhavesh Soni

Reputation: 198

Kindly below code snippet which will give you links store in weblist:

import java.awt.AWTException;
import java.util.List;
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;
import org.testng.annotations.Test;

public class Testing {
    public static WebDriver driver;

    @Test
    public void test() throws InterruptedException, AWTException {
        System.setProperty("webdriver.chrome.driver", "./Driver/chromedriver");
        driver = new ChromeDriver();
        driver.get("https://www.pibr.org.pl/pl/search/auditor?biegli=1&firmy=1&name=&post_code=&city=Warszawa");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
        List<WebElement> fromDropDwon = driver.findElements(By.xpath("/html/body/div[2]/div/div[2]/div/h3/a"));
        for (WebElement element : fromDropDwon) {
            System.out.println(element.getAttribute("href"));
        }
    }
}

Output:

enter image description here

Upvotes: 0

Guy
Guy

Reputation: 50809

The xpath should be "//div[@class='inner-results firma']", with quotation marks around the class attribute. You should also use findElements to get more than one result

MyWebDriver.findElements(By.xpath("//div[@class='inner-results firm']")).click();

As a side note, variables in Java should start with lower case, MyWebDriver -> myWebDriver

Upvotes: 4

Sameer Arora
Sameer Arora

Reputation: 4507

You need to put the class name in single quotes, please use the below command to get the links: MyWebDriver.findElement(By.xpath("//div[@class='inner-results firma']")).click();

Though this would click only on the first element of the class, if you want to get all the links and then click on the first link then you can use: MyWebDriver.findElements(By.xpath("//div[@class='inner-results firma']")).get(0).click(); and by using this xpath you can click on any link mentioned on the page by sending the index in the get(index) method.

Upvotes: 2

Related Questions