简体   繁体   中英

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?

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

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.

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM