Selenium 如何通过 XPath 访问 WebElement?

我需要访问本网站上搜索结果的链接(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."

如何访问所有结果链接?


HUX布斯
浏览 93回答 3
3回答

ibeautiful

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) 方法中的索引。

aluckdog

请在下面的代码片段中为您提供链接存储在网络列表中: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 {&nbsp; &nbsp; public static WebDriver driver;&nbsp; &nbsp; @Test&nbsp; &nbsp; public void test() throws InterruptedException, AWTException {&nbsp; &nbsp; &nbsp; &nbsp; System.setProperty("webdriver.chrome.driver", "./Driver/chromedriver");&nbsp; &nbsp; &nbsp; &nbsp; driver = new ChromeDriver();&nbsp; &nbsp; &nbsp; &nbsp; driver.get("https://www.pibr.org.pl/pl/search/auditor?biegli=1&firmy=1&name=&post_code=&city=Warszawa");&nbsp; &nbsp; &nbsp; &nbsp; driver.manage().window().maximize();&nbsp; &nbsp; &nbsp; &nbsp; driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);&nbsp; &nbsp; &nbsp; &nbsp; List<WebElement> fromDropDwon = driver.findElements(By.xpath("/html/body/div[2]/div/div[2]/div/h3/a"));&nbsp; &nbsp; &nbsp; &nbsp; for (WebElement element : fromDropDwon) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(element.getAttribute("href"));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}输出:
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java