I am new bee of the automation testing. On my code, I am using the JavaScript on my Selenium automation test script (on using the JUnit). I am trying to find the current window title:
driver = new ChromeDriver();
js = (JavaScriptExecutor)driver;
driver.get(//passed url);
//after the log in my Org. I execute the command below
//to get the title of the current window I execute the below command
js.executeScript("document.getElementsByTagName('title').innerHTML;");
But the above command will return the answer as the null instant of
getting the title of the window. So does anyone know what's wrong with
my command?
But I get the title of the window on executing on the console log of the page. So I don't know what's wrong with my code.
Thanks.
Mohan Raj S.
Change the following line:
document.getElementsByTagName('title').innerHTML
to:
return document.getElementsByTagName('title')[0].innerHTML
in code it will be:
js.executeScript("return document.getElementsByTagName('title')[0].innerHTML;");
getElementsByTagName returns array of elements. So we need to pass the index value.
Web driver interface provides get title method. It is very simple.
String title=driver.getTitle();
System.out.println("Title is" + title);
You could do it like this also
function titleCheck() {
promise = driver.getTitle();
promise.then(function(title) {
console.log("The title is: " + title);
});
}
reference: https://blog.testproject.io/2018/03/08/selenium-javascript-best-practices/
though their var test- stuff doesn't work for me I had to remove it.
JavascriptExecutor js = (JavascriptExecutor)driver;
String text = js.executeScript("return document.title;").toString();
Related
I am trying to fetch of Frame after switching but it is still returning Title of Main WebPage. Sharing code and DOM details of Frame:
WebDriver driver = new ChromeDriver();
driver.get("http://www.dwuser.com/education/content/the-magical-iframe-tag-an-introduction/");
List<WebElement> IframaList=driver.findElements(By.tagName("iframe"));
System.out.println("total number of frame is "+IframaList.size());
for(WebElement e : IframaList){
System.out.println( e.getAttribute("name"));
}
driver.switchTo().frame("myDemoFrame");
System.out.println(driver.getTitle());
Dom Structure :
Note: I checked RemoteWebdriver Implementation of gettitle() and It says that It returns the title of Page. Does it mean the Title of the WebPage only?
The function getTitle() only returns the top level Title
Refer to the document below for more info.
This command returns the document title of the current top-level browsing context, equivalent to calling document.title.
https://www.w3.org/TR/webdriver1/#get-title
After switch to <iframe> you can get the title with following approach:
driver.switchTo().frame("myDemoFrame");
if(driver.findElements(By.tagName("title")).size()>0) {
String currentTitle = driver.findElement(By.tagName("title")).getAttribute("innerHTML");
System.out.println(currentTitle);
}
I have followig HTML code and want X path for the text "Analytics & Research"
<div id="LLCompositePageContainer" class="column-wrapper">
<div id="compositePageTitleDiv">
<h1 class="page-header">Analytics & Research</h1>
</div>
I am getting following xpath using chrome, but that didnt work.
//*[#id="compositePageTitleDiv"]
this is my code
WebElement header = driver.findElement(By.xpath("//div[#id='LLCompositePageContainer']/div[#id='compositePageTitleDiv']/h1[#class='page-header']"));
String header2 = header.getText();
System.out.println(header2);
and following error I am getting
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
Unable to find element with xpath ==
//div[#id='LLCompositePageContainer']/div[#id='compositePageTitleDiv']/h1[#class='page-header']
(WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10.34 seconds For documentation on this
error, please visit:
http://seleniumhq.org/exceptions/no_such_element.html
Please try to use the below xpath:
driver.findElement(By.xpath(".//div[#id='compositePageTitleDiv']/h1")).getText();
If the element is inside the iframe. Then use the below code:
// Switching to the frame
driver.switchTo().frame(<name>);
// Storing the value of the Analytics & Research
String text = driver.findElement(By.xpath(".//div[#id='compositePageTitleDiv']/h1")).getText();
// Switching back to original window
driver.switchTo().defaultContent();
Hope this helps.
This is how it can be used :
WebElement element= driver.findElement(By.xpath("//*[#id='compositePageTitleDiv']"));
Or in case it is nested, can be accessed like this as well
WebElement element = driver.findElement(By.xpath("//html/body/div[3]/div[3]/"));
this is just a rough syntax.
No need to use Xpath here if you could simply locate the element using By.id(). Asuming are using Java, you should try as below :-
WebElement el = drive.findElement(By.id("compositePageTitleDiv"));
String text = el.getText();
Edited :- If element not found, may it is timing issues you need to implement WebDriverWait to wait for element until visible on the page as below :-
WebDriverWait wait = new WebDriverWait(webDriver, implicitWait);
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("compositePageTitleDiv")));
String text = el.getText();
Note :- if your element is inside any frame, you need to switch that frame before finding element as :- driver.switchTo().frame("your frame name or id");
Hope it helps..:)
You can also use
//div[#id='LLCompositePageContainer']/div[#id='compositePageTitleDiv']/
h1[contains(text(),'Analytics')]
This is the best way to reach to the specific web element, using contains minimize the chances of error.
The correct xpath is
//div[#id='LLCompositePageContainer']
/div[#id='compositePageTitleDiv']
/h1[#class='page-header']
But you could have find your answer easily with some researchs on google...
I just tried to open the first search result of the youtube link.
Here is my code. Since the youtube results are in iFrame, I used SwitchTo.frame()method.
String browser = "Chrome";
WebDriver b = null;
if(browser.equals("Chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
b = new ChromeDriver();
}
else if (browser.equals("firefox")) {
b = new FirefoxDriver();
}
b.get("http://www.youtube.com/");
b.findElement(By.xpath("//*[#id='masthead-search-term']")).sendKeys("selenium tutorial for beginner");
b.findElement(By.xpath("//*[#id='masthead-search-term']")).sendKeys(Keys.RETURN);
b.switchTo().frame("pyv-iframe"); //youtube search results are in iframe
//b.findElement(By.linkText("Selenium IDE Demo - Quick Beginner's Tutorial")).click();
b.findElement(By.xpath("//*[#id='search-results']/li[1]/div[2]/h3/a/span")).click();
While running this code it returns as
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element
at findElement By xpath. Please tell me what am I missing. Please see me as a newbie to Selenium.
I'm not sure why you are saying that the results are in an <iframe>... I'm not seeing an iframe. Here is your script using the getting started with selenium framework:
#Config(url="http://youtube.com")
public class YouTubeTest extends AutomationTest {
#Test
public void myTest() {
setText(By.id("masthead-search-term"), "selenium tutorial for beginner")
.click(By.id("search-btn"))
// navigate to a search result based on index
.click(By.cssSelector("ol#search-results > li:nth-child(X) a.yt-uix-tile-link"))
;
}
}
on the click(By.cssSelector you need to replace the X value with 1, 2, etc.. whatever the index of the link you want to click is.
(If you aren't using that framework you can easily translate the code and extract the selectors I use)
I did investigate on the Youtube page in Selenium IDE and it did get me these results:
driver = new FirefoxDriver();
baseUrl = "http://www.youtube.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl + "/results?search_query=selenium&sm=3");
driver.findElement(By.id("masthead-search-term")).clear();
driver.findElement(By.id("masthead-search-term")).sendKeys("selenium");
driver.findElement(By.cssSelector("span.yt-ui-ellipsis-wrapper")).click();
Please note the last line: Thats where I clicked on the first search result. After investigating the Youtube page with Web Developer tools I realised that here is a iframe but it contains only some tracking code for AdSense (my guess)
General note: Always try to investigate with Selenium IDE first. It saved me from a lots of nightmares about my selenium code ;)
I'm trying to automate the webpage "http://www.quikr.com",when I open this you will get a pop up window first saying "Please Choose Your Location" then after closing it , I can see the main page of quikr.
I tried closing that Popup page by automation ,but not able to do
Tried using xpath
driver.findElement(By.xpath("//*[#id='csclose']/strong")).click();
Tried using className
driver.findElement(By.className("cs-close cs-close-v2")).click();
Tried using id
driver.findElement(By.id("csclose")).click();
Please help me with this
to close multiple popups in webdriver and switch to parent window
String parent = driver.getWindowHandle();
Set<String> pops=driver.getWindowHandles();
{
Iterator<String> it =pops.iterator();
while (it.hasNext()) {
String popupHandle=it.next().toString();
if(!popupHandle.contains(parent))
{
driver.switchTo().window(popupHandle);
System.out.println("Popu Up Title: "+ driver.switchTo().window(popupHandle).getTitle());
driver.close();
The Following Code Works for Me to Handle Pop Up/ Alerts in Selenium Webdriver
Just Copy Paste this Code After the Event which is triggering the Pop up/Alert i.e after clicking on save.
if(driver.switchTo().alert() != null)
{
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
alert.dismiss(); // alert.accept();
}
in your case you try to run this code at starting of the code bcz it will directly close the pop up
Since this is a JavaScript modal, when the page finishes loading the JavaScript code could still be running. The solution is to wait until the button to close the modal be displayed, close it and then follow with your test. Like this:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementIsVisible(By.Id("csclose")));
driver.FindElement(By.Id("csclose")).Click();
Tested myself and works fine.
Hope it helps.
i have tried it in ruby and this one works
see if this can help you in any way :)
require 'selenium-webdriver'
require 'test/unit'
require 'rubygems'
class Tclogin < Test::Unit::TestCase #------------ define a class----------------
def setup
##driver = Selenium::WebDriver.for :firefox
##driver.navigate.to "http://www.quikr.com" #---- call url----
##wait = Selenium::WebDriver::Wait.new(:timeout => 60) # seconds #----define wait------
end
def test_login
##driver.find_element(:css, "strong").click
end
end
you can also use follwing xpath
##driver.find_element(:xpath, "//a[#id='csclose']/strong").click
public void closePopup() throws Exception {
WebDriver driver = new InternetExplorerDriver();
driver.get("http://www.quikr.com/");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("csclose"))).click();
System.out.println("Successfully closed the start Popup");
}
Try driver.findElement(By.Id("csclose")).click(); I hope that will help
Simple pressing Alt + F4 buttons worked for me, e.g.:
driver.findElement(By.cssSelector("html body div div img")).sendKeys(Keys.chord(Keys.ALT, Keys.F4));
I am trying to use Selenium's Xpath ability to be able to find an set of elements. I have used FirePath on FireFox to create and test the Xpath that I have come up with and that is working just fine but when I use the Xpath in my c# test with Selenium nothing is returned.
var MiElements = this._driver.FindElements(By.XPath("//div[#class='context-menu-item' and descendant::div[text()='Action Selected Jobs']]"));
and the Html looks like this:-
Can Anyone please point me right as everything that I have read the web says to me that this Xpath is correct.
Thanking you all in-advance.
Please post the actual HTML, so we can simply "drop it in" into a HTML file and try it ourselves but I noticed that there is a trailing space at the end of the class name:
<div title="Actions Selected Jobs." class="context-menu-item " .....
So force XPath to strip the trailing spaces first:
var MiElements = this._driver.FindElements(By.XPath("//div[normalize-space(#class)='context-menu-item' and descendant::div[text()='Action Selected Jobs']]"));
Perhaps you don't take into consideration the time that the elements need to load and you look for them when they aren't yet "searchable". UPDATE I skipped examples regarding this issue. See Slanec's comment.
Anyway, Selenium recommends to avoid searching by xpath whenever it is possible, because of being slower and more "fragile".
You could find your element like this:
//see the method code below
WebElement div = findDivByTitle("Action Selected Jobs");
//example of searching for one (first found) element
if (div != null) {
WebElement myElement = div.findElement(By.className("context-menu-item"));
}
......
//example of searching for all the elements
if (div != null) {
WebElement myElement = div.findElements(By.className("context-menu-item-inner"));
}
//try to wrap the code above in convenient method/s with expressive names
//and separate it from test code
......
WebElement findDivByTitle(final String divTitle) {
List<WebElement> foundDivs = this._driver.findElements(By.tagName("div"));
for (WebElement div : foundDivs) {
if (element.getAttribute("title").equals(divTitle)) {
return element;
}
}
return null;
}
This is approximate code (based on your explanation), you should adapt it better to your purposes. Again, remember to take the load time into account and to separate your utility code from the test code.
Hope it helps.