繁体   English   中英

Selenium-如何在Java中一次获取两个HTML节点的属性?

[英]Selenium - How to get the attributes of two HTML nodes at once in Java?

我现在正在一个程序上工作几个小时,任何我都感到困惑。 所以这笔交易是我想做一个蒸汽价格表。 这是网站

假设我要列出价格最高的两个商品的名称和价格。 如果您查看html源代码,将会看到找到的前2个项目的命名如下:

id=result_0_name
id=result_1_name

但是在结果0和结果1中,价格只是调用:“ market_table_value”

我正在尝试这样打印:

System.out.println(driver.findElement(By.id("result_0_name"))).getAttribute("market_table_value");

但是后来我意识到程序无法识别出我想要“ result0”的价格,也许总会给我一个静态数字,因为没有唯一的市场价值数字。

对不起,如果我让你们感到困惑,但是我真的希望您能理解我,因为我的想法被炸了,我也不知道该怎么做:/

您要在此处使用xPath:

  • 获取商品名称: //*[@id="result_0_name"]
  • 获取商品价格: //*[@id="result_0"]/div[1]/span[1]/span

Java代码

public class Item {
     private String name;
     private String price;

     public Item(String name, String price) {
        this.name=name;
        this.price=price;
     }

     public String getName() {
        return name;
     }

     public String getPrice() {
        return price;
     }
}

/**
 *
 * Get item at position {@code position} or {@code null} if not found.
 *
 */
private Item getHighestItem(int position, WebDriver driver) {
   Item item=null;

   try {
      int index = position-1;
      String name = driver.findElement(By.xPath("//*[@id='result_" + index + "_name']")).getText();
      String price = driver.findElement(By.xPath("//*[@id='result_" + index + "']/div[1]/span[1]/span")).getText();

      item = new Item(name, price);
   } catch(NoSuchElementException nse) {
       // handle exception here...
   }

   return item;
}

样品用法

WebDriver driver = ...;
...
Item firstItem = getHighestItem(1, driver); // get Most expensive item 
Item secondItem = getHighestItem(2, driver); // get 2nd Most expensive item
...

暂无
暂无

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

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