如何在 Java 中使用 Selenium Webdriver 获取标签值

我尝试使用此代码进行实验。我试图建立一个系统来从网站获取数据并使用拉格朗日插值方法来创建多项式。我正在用 Java 研究 Selenium 来做到这一点。看看我开发了什么。


package com.gustavo.seleniumTest;


import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;


public class seleniumTest {


public static void main(String[] args) {


    System.setProperty("webdriver.gecko.driver", "/home/gustavo/geckodriver");

    WebDriver driver = new FirefoxDriver();


    String valor;


    driver.get("http://cotacoes.economia.uol.com.br/acao/cotacoes-historicas.html?codigo=PETR4.SA&size=200&page=1&period=");

    valor = driver.findElement(By.xpath(".//*[@class='odd']")).getText();

    System.out.println(valor);

}

注意:我使用的是 linux 和 Firefox。


森林海
浏览 432回答 2
2回答

子衿沉夜

您需要修改定位器,如果要获取所有元素,则需要使用driver.findElements()方法。试试下面的 XPath 定位器,它将识别表的行数:String xPath = "//table[@id='tblInterday']/tbody//tr";你可以像这样得到行的大小:int rows = driver.findElements(By.xpath(xPath)).size();您可以使用循环遍历整行,例如for如下循环:for(int i=1;i<rows;i++) {}下面的 XPath 将根据行索引号标识每行中的列数:String xPath = "//table[@id='tblInterday']/tbody//tr[row index number]/td";由于行数很多,您可以将行索引传递给上面的 XPath,如下所示:for(int i=1;i<rows;i++) {&nbsp; &nbsp; driver.findElements(By.xpath(xPath+"["+i+"]/td"));}当我们使用driver.findElements()上面的方法时,它将保存所有列元素,我们可以循环并打印每个元素,如下所示:for(WebElement element : driver.findElements(By.xpath(xPath+"["+i+"]/td"))) {&nbsp; &nbsp; System.out.print(element.getText()+"\t");}代替driver.findElements(By.xpath(xPath+"["+i+"]/td")).forEach(e -> System.out.print(e.getText()+"\t"));和for(WebElement element : driver.findElements(By.xpath(xPath+"["+i+"]/td"))) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(element.getText()+"\t");&nbsp; &nbsp; }如果要正常打印。下面是使用 Java 8 的整个代码:import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;public class SeleniumTest {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; System.setProperty("webdriver.chrome.driver", "C:\\NotBackedUp\\chromedriver.exe");&nbsp; &nbsp; &nbsp; &nbsp; WebDriver driver = new ChromeDriver();&nbsp; &nbsp; &nbsp; &nbsp; driver.get("http://cotacoes.economia.uol.com.br/acao/cotacoes-historicas.html?codigo=PETR4.SA&size=200&page=1&period=");&nbsp; &nbsp; &nbsp; &nbsp; String xPath = "//table[@id='tblInterday']/tbody//tr";&nbsp; &nbsp; &nbsp; &nbsp; int rows = driver.findElements(By.xpath(xPath)).size();&nbsp; &nbsp; &nbsp; &nbsp; for(int i=1;i<rows;i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; driver.findElements(By.xpath(xPath+"["+i+"]/td")).forEach(e -> System.out.print(e.getText()+"\t"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}我希望它有帮助...

沧海一幻觉

在 DOM 中发布元素(标签之间的全部内容)。如果它是标签内的文本,您的代码将起作用,但如果文本位于 value 参数内,则需要 getProperty("value") 才能从元素中提取它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java