任务-从AMAZON打印所有产品描述和价格 我使用列表并使用for循环对其进行迭代
发生-仅打印一种产品信息和价格,并打印直到for循环符合条件
代码:
List<WebElement> products = driver.findElements(By.xpath("//div[@class=\"s-result-list s-search-results sg-row\"]//descendant::span[@class=\"a-size-base-plus a-color-base a-text-normal\"]"));
int count = products.size();
System.out.println(count);
//using XLS reader class to make runtime excel sheet and add column
Xls_Reader reader = new Xls_Reader(prop.getProperty("Excel"));
if (!reader.isSheetExist("ProductData")) {
reader.addSheet("ProductData");
reader.addColumn("ProductData", "Name of Product");
reader.addColumn("ProductData", "Price of Product");
}
// for loop to set cell data of product description and product price
for (int i = 0; i <= count; i++) {
String prod_desc = driver.findElement(By.xpath("//span[@class=\"a-size-base-plus a-color-base a-text-normal\"]")).getText();
System.out.println("Done111");
reader.setCellData("ProductData", "Name of Product", i, prod_desc);
String prod_price= driver.findElement(By.xpath("//div[@class=\"a-section a-spacing-none a-text-center\"]//descendant::span[@class=\"a-price-whole\"]"
)).getText(); System.out.println(prod_price);
reader.setCellData("ProductData", "Price of Product", i, prod_price);
}
}
catch(Exception e) {
e.printStackTrace();
}
结果:
Amazon.in: wrist watches
26
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
Done111
3,746
PASSED: clickOnSearchBtnTest
答案 0 :(得分:0)
您可以添加html吗。这将有助于解决您的问题
与此同时,请尝试以下操作:
library(dplyr)
library(tidyr)
df1 %>%
pivot_longer(cols = -X1) %>%
separate_rows(value, sep="(?<=\\]),\\s*") %>%
transmute(Group = LETTERS[row_number()], ID = value) %>%
mutate(ID = str_extract_all(ID, "\\d+")) %>%
unnest(c(ID))
# A tibble: 13 x 2
# Group ID
# <chr> <chr>
# 1 A 1
# 2 A 2
# 3 A 3
# 4 B 4
# 5 B 6
# 6 B 5
# 7 C 7
# 8 C 8
# 9 D 9
#10 D 10
#11 D 11
#12 D 12
#13 D 13
答案 1 :(得分:-1)
在xpath之后,您将从首页获得所有描述的列表
List<WebElement> descriptions = driver.findElements(By.xpath(".//span[@class='a-size-base-plus a-color-base a-text-normal']"));
使用xpath之后,您将获得所有价格的列表
List<WebElement> prices = driver.findElements(By.xpath(".//span[@class='a-price-whole']"));
由于描述列表和价格列表的计数都将相同,因此,我们将迭代循环并从两个列表的每个元素中获取文本。
for(int i = 0; i < descriptions.size(); i++) {
String desc = descriptions.get(i).getText();
String price = prices.get(i).getText();
System.out.println(desc +":"+ price);
}