![](/img/trans.png)
[英]How to get product reviews and then click <a> element of product with most reviews (Selenium, Java)
[英]How to select the product with the most product reviews
實際測試是把go放到ebay上,點擊搜索框,輸入“iphone 8”,然后回車,然后點擊商品評分最高的商品。 到目前為止,這是我的代碼
`WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.get("https://www.ebay.com/");
driver.manage().window().maximize();
driver.findElement(By.id("gh-ac")).sendKeys("iphone 8", Keys.ENTER);`
這里的問題是顯示產品評論的網絡元素與我們需要單擊以進入產品頁面的網絡元素不同。
嘗試查找帶有 xPath 的元素。
以下是在 eBay 搜索結果中找到的前 2 個 iPhone 8 完整 xPath 的示例。
Product Review:
/html/body/div[5]/div[5]/div[2]/div[1]/div[2]/ul/li[1]/div/div[2]/div[3]/a/span/span[1]
Image:
/html/body/div[5]/div[5]/div[2]/div[1]/div[2]/ul/li[1]/div/div[1]/div/a/div/img
Product Review:
/html/body/div[5]/div[5]/div[2]/div[1]/div[2]/ul/li[2]/div/div[2]/div[3]/a/span/span[1]
Image: /html/body/div[5]/div[5]/div[2]/div[1]/div[2]/ul/li[2]/div/div[1]/div/a/div/img
我看到了/li[x]
之前的模式
您可以遍歷該頁面上的整個產品列表,並將每個產品設置為帶有鏈接和產品評論屬性的 object,以便您可以進一步處理數據。
請查看下面的代碼,如果您遇到任何問題,請告訴我。
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get("https://www.ebay.com/");
// Enter value in Search textbox and press enter
WebElement SearchTextbox = wait.until(ExpectedConditions.presenceOfElementLocated(
(By.xpath("//input[contains(@id,\"gh-\") and @type=\"text\"]"))));
SearchTextbox.click();
SearchTextbox.sendKeys("iphone 8");
SearchTextbox.sendKeys(Keys.ENTER);
// Collected all the product review WebElements
List<WebElement> ProductReviews = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy
(By.xpath("//span[@class=\"s-item__reviews-count\"]/span[1]")));
// Made a list to accumulate all products number.
ArrayList<Integer> mylist = new ArrayList<>();
// Loop through all the WebElement and Extract number from String i.e. "70 product ratings"
// (Extracting 70 in above case)
for (WebElement ProdInfo : ProductReviews) {
try {
mylist.add(Integer.parseInt(ProdInfo.getText().split("product")[0].trim()));
} catch (Exception ignored) {
}
}
// Printed mylist to verify
// and Extracted max number so that we can use that in xpath to search exact element and click on it.
System.out.println(mylist);
Integer max_number = Collections.max(mylist);
driver.findElement(By.xpath(String.format("//span[text()=\"%s product ratings\"]", max_number))).click();
如果您在執行上述代碼時遇到任何問題,請立即告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.