- load the url https://sfo-demo.herokuapp.com/model-portfolio in chrome
- able to see 2 tabs (3 Portfolio recommendations based on your preferences & 15 other portfolio choices available)
- Gettext performed on these 2 elements gets the same text (that is displayed)
- Resize the window to 667, 375 (d.manage().window().setSize(new Dimension(667, 375));)
- The text of those 2 tabs changed. Now the gettext() performed on those 2 elements wont fetch any text
Asked
Active
Viewed 168 times
0

arun kumar
- 1
- 1
-
Please always post your code and thrown exception if any. – pburgr Jun 10 '19 at 14:07
3 Answers
1
When you resize the window to 667, 375
the elements you see are from the mobile view and are located in different places within the DOM Tree. So you need to use a different Locator Strategy as follows:
Code Block:
ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.addArguments("start-maximized"); chromeOptions.addArguments("disable-infobars"); chromeOptions.addArguments("--disable-extensions"); WebDriver driver = new ChromeDriver(chromeOptions); driver.get("https://sfo-demo.herokuapp.com/model-portfolio"); System.out.println("Elements in list with full screen:"); System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("ul.model-portfolio-navs.hidden-sm.hidden-xs a"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList())); driver.manage().window().setSize(new Dimension(667, 375)); System.out.println("Elements in list with window resized:"); System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("ul.model-portfolio-navs.mobile.hidden-md.hidden-lg a"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList()));
Console Output:
Elements in list with full screen: [ 3 Portfolio recommendations based on your preferences , 15 other portfolio choices available ] Elements in list with window resized: [Recommended (3), Others (15)]

undetected Selenium
- 183,867
- 41
- 278
- 352
1
When you resize the window the DOM elements become stale and you need to execute WebDriver.findElements() function one more time to get updated elements.
You can use the same XPath locator for both cases for compatibility.
Example code:
ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://sfo-demo.herokuapp.com/model-portfolio");
List<String> textBeforeResize = driver.findElements(By.xpath("//a[@data-toggle='tab']"))
.stream()
.map(WebElement::getText)
.collect(Collectors.toList());
System.out.println("Before:");
textBeforeResize.forEach(System.out::println);
driver.manage().window().setSize(new Dimension(667, 375));
System.out.println("After:");
List<String> textAfterResize = driver.findElements(By.xpath("//a[@data-toggle='tab']"))
.stream()
.map(WebElement::getText)
.collect(Collectors.toList());
textAfterResize.forEach(System.out::println);
Demo:

Dmitri T
- 159,985
- 5
- 83
- 133
0
Agree with both previous answers. Using absolute xpath to pinpoint the different element location:
package arun;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import webdriverFactoryPatternUsingSupplier.*;
public class Q56527756 {
WebDriver driver = DriverFactory.getDriver(DriverType.CHROME);
@Test
public void demo() throws InterruptedException {
driver.get("https://sfo-demo.herokuapp.com/model-portfolio");
clickableByXpath("//*[@id=\"page-top\"]/div[3]/div[1]/nav/div[1]/a/img", 5);
WebElement no1 = byXpath("//*[@id=\"page-top\"]/div[3]/section/div[2]/div[3]/ul[1]/li[1]/a");
WebElement no2 = byXpath("//*[@id=\"page-top\"]/div[3]/section/div[2]/div[3]/ul[1]/li[2]/a");
String firstElementFirstTry = no1.getText();
String secondElementFirstTry = no2.getText();
System.out.println(firstElementFirstTry);
System.out.println(secondElementFirstTry);
driver.manage().window().setSize(new Dimension(667, 375));
// there are elementes fitting to no1's and no'2 xpath, but those are not the same, have no text
// after resize your two elements are moved in 'ul' level
WebElement no3 = byXpath("//*[@id=\"page-top\"]/div[3]/section/div[2]/div[3]/ul[2]/li[1]/a");
WebElement no4 = byXpath("//*[@id=\"page-top\"]/div[3]/section/div[2]/div[3]/ul[2]/li[2]/a");
String firstElementSecondTry = no3.getText();
String secondElementSecondTry = no4.getText();
System.out.println(firstElementSecondTry);
System.out.println(secondElementSecondTry);
driver.close();
driver.quit();
}
// custom wait method
public WebDriverWait waitSec(WebDriver driver, int sec) {
return new WebDriverWait(driver, sec);
}
public WebElement byXpath(String xpath) {
WebElement element = driver.findElement(By.xpath(xpath));
return element;
}
public WebElement clickableByXpath(String xpath, int sec) {
WebElement element = waitSec(driver, sec).until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)));
return element;
}
}
Output:
Starting ChromeDriver 74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}) on port 15890
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
[1560178038.495][WARNING]: This version of ChromeDriver has not been tested with Chrome version 75.
Čer 10, 2019 4:47:19 ODP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
3 Portfolio recommendations based on your preferences
15 other portfolio choices available
Recommended (3)
Others (15)
And the factory if you wanna try it by yourself (just edit paths):
package webdriverFactoryPatternUsingSupplier;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class DriverFactory {
private static final Map<DriverType, Supplier<WebDriver>> driverMap = new HashMap<>();
public static String chromedriverPath = "C:\\Users\\pburgr\\Desktop\\selenium-tests\\GCH_driver\\chromedriver.exe";
public static String chromeProfilePath = "C:\\Users\\pburgr\\AppData\\Local\\Google\\Chrome\\User Data";
public static String geckodriverPath = "C:\\Users\\pburgr\\Desktop\\selenium-tests\\FF_driver_0_23\\geckodriver.exe";
public static WebDriver driver;
//chrome driver supplier
private static final Supplier<WebDriver> chromeDriverSupplier = () -> {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=" + chromeProfilePath);
driver = new ChromeDriver(options);
driver.manage().window().maximize();
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
return driver;
};
//firefox driver supplier
private static final Supplier<WebDriver> firefoxDriverSupplier = () -> {
FirefoxOptions options = new FirefoxOptions();
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile selenium_profile = allProfiles.getProfile("selenium_profile");
options.setProfile(selenium_profile);
options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
System.setProperty("webdriver.gecko.driver", geckodriverPath);
driver = new FirefoxDriver(options);
driver.manage().window().maximize();
return driver;
};
//add more suppliers here
//add all the drivers into a map
static{
driverMap.put(DriverType.CHROME, chromeDriverSupplier);
driverMap.put(DriverType.FIREFOX, firefoxDriverSupplier);
}
//return a new driver from the map
public static final WebDriver getDriver(DriverType type){
return driverMap.get(type).get();
}
}
and enum:
package webdriverFactoryPatternUsingSupplier;
public enum DriverType {
CHROME,
FIREFOX,
// SAFARI, not implemented
// IE; not implemented
}

pburgr
- 1,722
- 1
- 11
- 26