繁体   English   中英

如何通过 Selenium 的 XPath 访问 WebElement?

[英]How to access WebElement by XPath by Selenium?

我需要访问该网站上搜索结果的链接( https://www.pibr.org.pl/pl/search/auditor?biegli=1&firmy=1&name=&post_code=&city=Warszawa )并将它们放在WebElement ,但是我无法按课程或任何东西找到它们。 使用xpath

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

我收到此错误:

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

如何访问所有结果链接?

xpath应该是"//div[@class='inner-results firma']" ,在class属性周围加上引号。 您还应该使用findElements来获得多个结果

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

作为旁注,Java 中的变量应以小写开头, MyWebDriver -> myWebDriver

您需要将类名放在单引号中,请使用以下命令获取链接: MyWebDriver.findElement(By.xpath("//div[@class='inner-results firma']")).click();

虽然这只会单击类的第一个元素,但如果您想获取所有链接,然后单击第一个链接,则可以使用: MyWebDriver.findElements(By.xpath("//div[@class='inner-results firma']")).get(0).click(); 通过使用此 xpath,您可以通过在 get(index) 方法中发送索引来单击页面上提到的任何链接。

请在下面的代码片段中提供链接存储在网络列表中:

 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")); } } }

输出:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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