如何使用Selenium并排打印一些文本?

时间:2019-04-16 08:18:03

标签: selenium-webdriver

我必须同时打印酒店名称和价格

示例: oyo Rooms-2000rs

我尝试使用Selenium Web驱动程序。

WebDriver driver = new ChromeDriver();
        String baseUrl = "https:www.teletextholidays.co.uk";
        driver.get(baseUrl);
        driver.manage().window().maximize();

          WebElement all_Inclusive = driver.findElement(By.xpath("//*[@class='header pstn-fxd edge txt-center fixed-nav-container']//div[@class='show-on-desktop inblock']//a[@class='top-nav-allinclusive nav-item txt-white inblock hover-out allinclusivelink']")); 
          all_Inclusive.click(); WebElement all_hotels =driver.findElement(By.xpath("//*[@class='lg-flex-box']"));
          JavascriptExecutor js = (JavascriptExecutor) driver;
          js.executeScript("arguments[0].scrollIntoView();", all_hotels);
          List<WebElement> hotellist = driver.findElements(By.xpath("//*[@class='deal-price pstn-reltv grid-stay items-center space-between']//span[@class='dstn-name txt-bold']")); 
          System.out.println(hotellist.get);
          List<WebElement> pricelist = driver.findElements(By.xpath("//*[@class='deal-price pstn-reltv grid-stay items-center space-between']//span[@class='tth-price font-bold txt-sunset']" ));
          /*for (WebElement hotel : hotellist) {
              System.out.println(hotel.getText());
          }*/
          for (WebElement price : pricelist) {
              System.out.println(price.getText());  
              if(price.getText().contains("157")) {
                  System.out.println(hotel);
              }
          }

预期输出: Oyo-1000,alpha-2345

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我们需要先获取父元素,然后从该元素中查找酒店和价格,以保持它们之间的关联。

尝试以下代码以打印酒店-价格格式。

List<WebElement> listOfLinks = driver.findElements(By.cssSelector("a>div.deal-price"));

for(WebElement link: listOfLinks) {
    System.out.print(link.findElement(By.cssSelector(".from-price>.dstn-name")).getText());
    System.out.print(" - ");
    System.out.println(link.findElement(By.cssSelector(".txt-right .tth-price")).getText());
}