How to handle Mouseover in Selenium 2 API - selenium

String strPrimaryNav = "MEN";
String strSecondaryNav = "Shoes";
String strTertiaryNav = "Golf";
driver.findElement(By.linkText(strPrimaryNav)).click();
WebElement weSecNav = driver.findElement(By.className("secondaryButton").linkText(strSecondaryNav));
Mouse mouse = ((HasInputDevices) driver).getMouse();
mouse.mouseDown(((Locatable)weSecNav).getCoordinates());
//just trying with for loop as the tertiary popup disappears quickly and hence getting ElementNotVisible Exception
for (int i = 0 ; i< 2; i++){
mouse.mouseDown(((Locatable)weSecNav).getCoordinates());
//mouse.mouseMove(((Locatable)weSecNav).getCoordinates(), 0, 0 );
//WebElement weTerNav = driver.findElement(By.className("tertiaryButton").linkText(strTertiaryNav));
WebElement weTerNav = driver.findElement(By.linkText(strTertiaryNav));
boolean isSecDisplayed = ((RenderedWebElement)weTerNav).isDisplayed();
System.out.println("isDisplayed: " + isSecDisplayed);
System.out.println(" " + ((RenderedWebElement)weSecNav).getAttribute("href"));
System.out.println(" " + ((RenderedWebElement)weSecNav).getValueOfCssProperty("action"));
weTerNav.click();
}
I was trying the below code using selenium 2 but, the tertiary popup not stays long to click it and hence getting ElementNotVisible exception at Tertiary click.

You can at least check that the element is visible before you send your click:
Selenium s = new WebDriverBackedSelenium( driver, URL );
s.waitForCondition( "!( document.getElementById('.....') === null )", "20000" );
s.click( .... );
This avoids the exception. I'm not sure there is a way to make the popup stay any longer than it should.

Related

A loop for refreshing page that stop when a button/xpath is clickable

trying to create a loop that refreshes the page continuously until button or xpath becomes available then it will break (dont bully my poor coding i'm new)
if Date == '1':
bool (buttonActive) == False;
list <WebElement> element = driver.find_element_by_xpath('//*[#id="booking-slots-slider"]/div[1]/button')
while (buttonActive):
if (element.size() > 0):
buttonActive = True;
element.get(0).click();
else:
driver.refresh()
List<WebElement> add = driver.find_element_by_xpath('//*[#id="booking-slots-slider"]/div[1]/button')

How can I print all the submenu of main menu in webdriver

I want to print the submenu text of mainmenu of first list[Electronics] of
in selenium webdriver.
url : https://www.flipkart.com
But there is some issue to take the xpath of that sumMenu.
How can I take the xpath and all.
You can try with the following x-path to get all sub menus of main menu "Electronics"
//span[.='Electronics']/following-sibling::ul//li/a
Try the bellow code. Change value the String searchSubMenu = "Electronics"; if you want get text other sub menu, hope this helps.
driver.get("https://www.flipkart.com/");
//wait login popup and click
new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#class='_2AkmmA _29YdH8']")));
driver.findElement(By.xpath("//*[#class='_2AkmmA _29YdH8']")).click();
String searchSubMenu = "Electronics";
int totalSubMenu = driver.findElements(By.xpath("//*[contains(#class,'Wbt_B2')]")).size();
System.out.println("Search for : " +searchSubMenu);
for(int i=1; i<=totalSubMenu; i++) {
String getTextSubMenu = driver.findElement(By.xpath("(//*[contains(#class,'Wbt_B2')])[" +i +"]")).getText();
System.out.println("Get Sub Menu Title : "+ getTextSubMenu);
if (getTextSubMenu.equals(searchSubMenu)) {
driver.findElement(By.xpath("(//*[contains(#class,'Wbt_B2')])[" +i +"]")).click();
Thread.sleep(1000);
String targetAllGetText = driver.findElement(By.xpath("(//*[contains(#class,'_3GtRpC')])[" +i +"]")).getText();
System.out.println(targetAllGetText);
break;
}
}
driver.quit();
It will help you : Please try
String SubMenu = driver.findElement(By.xpath("Xpath of element")).getText();
System.out.println(SubMenu);
if you want Size:
int Size =driver.findElement(By.xpath("Xpath of element"));
System.out.println(Size);

Unable to drag and drop element for AngularJS application

I am trying to drag and drop elements on a AngularJS demo site, but I am not able to achieve results.
For my practice I am using https://marceljuenemann.github.io/angular-drag-and-drop-lists/demo/#/nested , and I am trying to drag & drop 'Item 7 (From dropzone B)' to 'Item 3 (In container 1)'.
I have used .getText() method to ensure that my xpath is pointing to the correct element. But still it is not working. Below is my code:
public void SetUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "F:\\Drivers\\chromedriver.exe");
d = new ChromeDriver();
d.manage().window().maximize();
d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
d.get("https://marceljuenemann.github.io/angular-drag-and-drop-lists/demo/#/nested");
Thread.sleep(2000);
((JavascriptExecutor)d).executeScript("scroll(4,400)");
WebElement src = d.findElement(By.xpath("html/body/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/div/div/ul/li[1]/div"));
System.out.println("The src element is:" +src.getText());
WebElement destn = d.findElement(By.xpath("html/body/div[2]/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/ul/li[1]/div/div[2]/ul/li/div"));
System.out.println("The src element is:" +destn.getText());
org.openqa.selenium.Point pt1 = src.getLocation();
org.openqa.selenium.Point pt2 = destn.getLocation();
int xCord1 = pt1.getX();
int yCord1 = pt1.getY();
int xCord2 = pt2.getX();
int yCord2 = pt2.getY();
System.out.println("The X & Y cordinate of the src is:" +xCord1+ " & " +yCord1);
System.out.println("The X & Y cordinate of the destn is:" +xCord2+ " & " +yCord2);
Actions ac = new Actions(d);
Action dragAndDrop = ac.clickAndHold(src).moveToElement(destn, 334, 661).release(destn).build();
dragAndDrop.perform();
}

How to get the all element id's of a screen in selenium

How can I get the all element id's of a screen in selenium?
Please refer to this screenshot
Element ID is getting changed every time the page loads. I used contains#id , start-with#id, but it doesn't work every time. Now I want to get all the element id's from the webpage, so I can select the exact element.
My webpage contains input text, buttons, drop-downs.
Use Xpath instead or cssSelector. If you persist on knowing all page ids as a list of String in java, try to execute a javascript function.
// The Firefox driver supports javascript
WebDriver driver = new FirefoxDriver();
// Go to the Google Suggest home page
driver.get("http://www.google.com/webhp?complete=1&hl=en");
ArrayList ids = (ArrayList)((JavascriptExecutor) driver).executeScript(
" var allElements = document.getElementsByTagName('*'); var allIds = []; "
+ " for (var i = 0, n = allElements.length; i < n; ++i) { "
+ " var el = allElements[i]; "
+ " if (el.id) { allIds.push(el.id); } } return allIds; "
);
Regards,
Alan Mehio
London, UK

How to check image requests for 404 using Selenium WebDriver?

What is the most convenient way using Selenium WebDriver to check if an URL GET returns successfully (HTTP 200)?
In this particular case I'm most interested in verifying that no images of the current page are broken.
Try this:
List<WebElement> allImages = driver.findElements(By.tagName("img"));
for (WebElement image : allImages) {
boolean loaded = ((JavaScriptExecutor) driver).executeScript(
"return arguments[0].complete", image);
if (!loaded) {
// Your error handling here.
}
}
You could use the getEval command to verify the value returned from the following JavaScript for each image on the page.
#Test
public void checkForBrokenImages() {
selenium.open("http://www.example.com/");
int imageCount = selenium.getXpathCount("//img").intValue();
for (int i = 0; i < imageCount; i++) {
String currentImage = "this.browserbot.getUserWindow().document.images[" + i + "]";
assertEquals(selenium.getEval("(!" + currentImage + ".complete) ? false : !(typeof " + currentImage + ".naturalWidth != \"undefined\" && " + currentImage + ".naturalWidth == 0);"), "true", "Broken image: " + selenium.getEval(currentImage + ".src"));
}
}
Updated:
Added tested TestNG/Java example.
I don't think that first response will work. When I src a misnamed image, it throws a 404 error as expected. However, when I check the javascript in firebug, that (broken) image has .complete set to true. So, it was a completed 404, but still a broken image.
The second response seems to be more accurate in that it checks that it's complete and then checks that there is some width to the image.
I made a python version of the second response that works for me. Could be cleaned up a bit, but hopefully it will help.
def checkForBrokenImages(self):
sel = self.selenium
imgCount = int(sel.get_xpath_count("//img"))
for i in range(0,imgCount):
isComplete = sel.get_eval("selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].complete")
self.assertTrue(isComplete, "Bad Img (!complete): "+sel.get_eval("selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].src"))
typeOf = sel.get_eval("typeof selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].naturalWidth")
self.assertTrue(typeOf != 'undefined', "Bad Img (w=undef): "+sel.get_eval("selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].src"))
natWidth = int(sel.get_eval("selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].naturalWidth"))
self.assertTrue(natWidth > 0, "Bad Img (w=0): "+sel.get_eval("selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].src"))
Instead of traversing in Java, it may be faster to call javascript only once for all images.
boolean allImgLoaded = (Boolean)((JavascriptExecutor) driver).executeScript(
"return Array.prototype.slice.call(document.images).every("
+ "function (img) {return img.complete && img.naturalWidth > 0;});");
One of the alternative solutions is analyzing web server logs after test executing. This approach allows to catch not only missed images, but css, scripts and other resources.
Description of how to do it is here.
Funda for Checking 404:
Basically 404s can be checked via HTTP Response of the URL.
Step 1: Import the Library for HTTPTestAPI
Step 2: Create the HTTPRequest.
String URL="www.abc.com";
HTTPRequest request = new HTTPRequest(URL);
//Get the response code of the URL
int response_code = request.getResponseCode();
//Check for 404:
if(response_code == 404)
FAIL -- THE URL is leading to 404.
else
PASS