Issue
I wants to open a new tab which contains a dynamic url. The url I am getting store in str
variable as shown below:
String str = WebPublish_URL.getText();
Now I wants a tab with url by using getText()
method.
Solution
There are 4 ways to do this. In below examples I am doing following steps,
- Launching
https://google.com
- Searching for
facebook
text and getting thefacebook
URL
- Opening
facebook
within and different tab.
Solution#1: Get the URL
value and load it in existing browser.
driver = new ChromeDriver(options);
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
driver.get(facebookUrl);
Solution#2: Using window handles
.
driver = new ChromeDriver(options);
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get(facebookUrl);
Solution#3: By creating new driver
instance. It's not recommended but it is also a possible way to do this.
driver = new ChromeDriver(options);
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
/*Create an another instance of driver.*/
driver = new ChromeDriver(options);
driver.get(facebookUrl);
Update with Selenium 4:
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
driver.switchTo().newWindow(WindowType.TAB);
driver.navigate().to(facebookUrl);
Answered By - Nandan A
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.