[英]Selenium - How to get the attributes of two HTML nodes at once in Java?
I am working on a program for hours now, any I am totaly confused. 我现在正在一个程序上工作几个小时,任何我都感到困惑。 So the deal is that I want to make a steam price lister. 所以这笔交易是我想做一个蒸汽价格表。 Here is the website . 这是网站 。
Let's say I want to list the two highest priced item's name and it's price. 假设我要列出价格最高的两个商品的名称和价格。 If you look at the html source you will see that the first 2 found item are named like this: 如果您查看html源代码,将会看到找到的前2个项目的命名如下:
id=result_0_name
id=result_1_name
But inside the result 0 and result 1 the price just called: "market_table_value" 但是在结果0和结果1中,价格只是调用:“ market_table_value”
And I am trying to print out like this: 我正在尝试这样打印:
System.out.println(driver.findElement(By.id("result_0_name"))).getAttribute("market_table_value");
But then I realised that the program won't recognise that I want the "result0"'s price, maybe it will always give me a static number, because there is no unique number for the market value. 但是后来我意识到程序无法识别出我想要“ result0”的价格,也许总会给我一个静态数字,因为没有唯一的市场价值数字。
Sorry if I confused you guys, but I really hope that you will understand me, because my mind got blown up, and I have no idea how to do it :/ 对不起,如果我让你们感到困惑,但是我真的希望您能理解我,因为我的想法被炸了,我也不知道该怎么做:/
You want to use xPath here: 您要在此处使用xPath:
//*[@id="result_0_name"]
获取商品名称: //*[@id="result_0_name"]
//*[@id="result_0"]/div[1]/span[1]/span
获取商品价格: //*[@id="result_0"]/div[1]/span[1]/span
Java code 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;
}
Sample usage 样品用法
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.