Need help in retrieving text of a tooltip with Selenium and Java - java

I am trying to get the text of the tooltip in the following image - with the code snippet shown below.
String xPath = "//div[#class="tooltip-inner"]/div";
we = driver.findElement(By.xPath(xPath));
if (null != we) {
Actions action = new Actions(driver);
action.moveToElement(we).moveToElement(driver.findElement(By.xpath(xPath))).click().build()
.perform();
String actualText = we.getText();
} else {
....generate an error
}
The code does not throw an error, but at the same time, text is not retrieved.
I tried to locate the /p and the /ul child elements and get their texts - but no luck either.
What am I not doing right? Any ideas?
Thanks.
-S-

Related

How to click button and delete input text with Selenium WebDriver

I'm able to navigate this page [here][1] and enter this website [here][2](TOKEN CREATED FOR EACH DEMO FOR THIS LINK)
I'm also able to extract the value from the round count using this xpath here #class,'coefficient'
I can locate the input element on the left hand side but only one text value is deleted. I want to delete all values and enter 50.
It also seems like I can locate the left hand side button because I'm not getting any exceptions or errors but the button is not clickable.
The below two lines:
firstInput.sendKeys(Keys.CONTROL + "a");
firstInput.sendKeys(Keys.DELETE);
is basically to clear the input field, since .clear() is not working as expected in this case, we'd have to do CTRL+a and then delete
A full code will look like this:
driver.manage().window().maximize();
driver.get("https://www.spribe.co/games/aviator");
WebDriverWait wait = new WebDriverWait(driver, 30);
try {
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),' Got it')]"))).click();
}
catch(Exception e){
e.printStackTrace();
}
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Play Demo ')]"))).click();
String originalWinHandle = driver.getWindowHandle();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Yes')]"))).click();
List<String> allHandles = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(allHandles.get(1));
WebElement firstInput = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[text()='BET']/ancestor::div[contains(#class,'feature')]/descendant::input")));
firstInput.sendKeys(Keys.CONTROL + "a");
firstInput.sendKeys(Keys.DELETE);
firstInput.sendKeys("20");
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[text()='BET']/.."))).click();

Selenium driver is freezing by switching tabs in browser

I'm trying to parse several goods. The problem is I can parse only first element.
To be specific: I need goods which were sorted by "Newest" on the website below. And I click this button before parsing.
driver.get("https://www.banggood.com/new-arrivals.html");
driver.findElementByCssSelector("body > div.lastest-box.J-loading-box > div > ul.filtrate.J-filter-list > li:nth-child(2)").click();
So I want to get info about each good doing like:
// save goods in arrayList
List<Article> articleList = new ArrayList<>();
WebElement ulElement = driver.findElement(By.cssSelector("div.box > ul.prt-list.J-prt-list"));
List<WebElement> liElements = industries.findElements(By.tagName("li"));
// using loop for parsing
for (WebElement element : liElements) {
String price = element.findElement(By.cssSelector("div.price-box > span.price.notranslate")).getText();
String title = element.findElement(By.cssSelector("p.title")).getText();
String url = element.findElement(By.cssSelector("span.img > a")).getAttribute("href");
// switch link to get img
String newUrl = url.replace("https://www.banggood.com/new-arrivals.html", url);
// open new tab using another url
((JavascriptExecutor)driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get(newUrl);
WebElement img = driver.findElement(By.id("landingImage"));
String srcImg = img.getAttribute("src");
articleList.add(new Article(srcImg, url, title, price));
// close new tab and back to the main window
((JavascriptExecutor)driver).executeScript("window.close()");
}
driver.close();
driver.quit();
}
Via debug I see it works:
but loop is going through only first element then the program is freezing. And I don't see any issues in the console.
Can someone tell me what I'm missing here? Thanks in advance.
Your driver is freezing because it is searching for a window that doesn't exist anymore. After closing your window you need to explicitly switch your window back to the first window:
// close new tab and back to the main window
((JavascriptExecutor)driver).executeScript("window.close()");
driver.switchTo().window(tabs.get(0));

Error trying to close a tab and switching to the other tab using selenium / java

I have a window with two tabs. I am trying to close the tab with a specific title and switch the control to the other tab.
Here is my code:
public static void closeTheWindowWithTitle(String title) {
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
String mainWindow = driver.getWindowHandle();
for(int i = 0; i < tabs.size(); i++) {
log.debug("switched to " + driver.getTitle() + " Window");
if(driver.getTitle().contains(title))
{
driver.switchTo().window(tabs.get(i));
driver.close();
log.debug("Closed the " + driver.getTitle() + " Window");
}
}
driver.switchTo().window(mainWindow);
}
When I run my code, I am getting the following exception:
org.openqa.selenium.NoSuchWindowException: no such window: target window already closed
from unknown error: web view not found
I am unable to figure out what is the problem. Please help.
I'm guessing, that the WindowHandle of your Main-Window got changed, somewhere along the way. You should be able to get your problem solved by doing something similar to the suggested solution here, i.e. getting all WindowHandles, and iterating over them and in the end switching to [0], which should be the only one left, after closing the second one.
I hope this will help you to fix your issue, i dont want to provide code fix and i want to explain you the details process step by step.
Open firefox/IE/Chrome browser and Navigate to https://www.bbc.co.uk
WebDriver driver = new AnyDriveryourusing();
// set implicit time to 30 seconds
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// navigate to the url
driver.get("https://www.bbc.co.uk");
Get the GU ID of the current (parent) window using getWindowHandle() method present in the webdriver and store the value in a String
// get the Session id of the Parent
String parentGUID = driver.getWindowHandle();
Click on the Open New Window button, application open new window with google page.
// click the button to open new window
driver.findElement(By.id("two-window")).click();
Thread.sleep(5000);
Get the GU IDs of the two windows (parent + google), using getWindowHandles() method present in the webdriver. Store the GU IDs in a Set Collection, this Set will have GU IDs of both parent and Child Browsers
// get the All the session id of the browsers
Set allGUID = driver.getWindowHandles();
iterate the Set of GUID values, and if the value is parent value skip it if not switch to the new window
// iterate the values in the set
for(String guid : allGUID){
// one enter into if block if the GUID is not equal to parent window's GUID
if(! guid.equals(parentGUID)){
//todo
}
}
Switch to window using switchTo().window() method, pass the GU ID of the child browser to this method.
// switch to the guid
driver.switchTo().window(guid);
Find the search bar in Google.com and search for "success"
driver.findElement(By.name("q")).sendKeys("success");
Close the Google tab/Window and return to parent tab/browser window
// close the browser
driver.close();
// switch back to the parent window
driver.switchTo().window(parentGUID);
You were close but you weren't switching windows before checking the title. I've updated the code to something that should work.
public static void closeTheWindowWithTitle(String title)
{
Set<String> tabs = driver.getWindowHandles();
String mainWindow = driver.getWindowHandle();
for(int i = 0; i < tabs.size(); i++)
{
// you need to switch to the window before checking title
driver.switchTo().window(tabs.get(i));
log.debug("switched to " + driver.getTitle() + " Window");
if(driver.getTitle().contains(title))
{
driver.close();
log.debug("Closed the " + driver.getTitle() + " Window");
break; // this breaks out of the loop, which I'm assuming is what you want when a match is found
}
}
driver.switchTo().window(mainWindow);
}

How to convert WebElement to a string for an 'if' statement in selenium/Java

I'm automating a webstore in selenium/Java. If the user hasn't selected the size of a product, a message comes up stating 'this is a required field' next to the size. I'm trying to write an 'if' statement that asserts whether this message is present and the action to take if it is, but I cannot get it to work. It would be something along the lines of this:
WebElement sizeIsRequiredMsg = driver.findElement(By.cssSelector("#advice-required-entry-select_30765)"));
WebElement sizeSmallButton = driver.findElement(By.cssSelector("#product_info_add > div.add-to-cart > div > button"))
if (sizeIsRequiredMsg.equals("This is a required field.")) {
action.moveToElement(sizeSmallButton);
action.click();
action.perform();
}
I've tried a few different variations using the 'this is a required field' message as a web element. Not sure if I need to convert the WebElement for the message to a string somehow? Or include a boolean? Can anyone help?
Try using getText() something like this:
EDIT I have added the correct cssSelectors and added try catch :
WebElement addToCartButton = driver.findElement(By.cssSelector("#product_info_add button"));
action.moveToElement(addToCartButton);
action.click();
action.perform();
try {
WebElement sizeIsRequiredMsg = driver.findElement(By.cssSelector(".validation-advice"));
WebElement sizeSmallButton = driver.findElement(By.cssSelector(".swatches-container .swatch-span:nth-child(2)"))
if (sizeIsRequiredMsg.getText() == "This is a required field.") {
action.moveToElement(sizeSmallButton);
action.click();
action.perform();
}
} catch (Exception e) {
System.out.println(e);
logger.log(Level.SEVERE, "Exception Occured:", e);
};
Hope this helps you!

Not able to extract password field in a modal window using CSS selector - Selenium Java

I am able to click on sign in link in the start page [a link] http://imgur.com , resulting modal window of username and password field. while I was trying to extract password field on the resulted page, found no elements of username and password fields. Even I checked the source code at that instant using driver.getPageSource(); and there is no sign of username or password elements. Following is the code used to extract password field from the specified URL.
pwd = driver.findElement(By.cssSelector("input[type='password']"));
code for clicking the modal window is
driver.findElement(By.partialLinkText("sign in")).click();
Later I found that they are using iframes so I started searching the password fields in each iframe as shown below.
List<WebElement> iFrames = null;
WebElement iFramePwd=null;
iFrames = driver.findElements(By.tagName("iframe"));
if (iFrames.size() > 0) {
for (int l = 0; l < iFrames.size(); l++) {
try{ driver.switchTo().frame(l);
}
catch(NoSuchFrameException ljn){
System.out.println(ljn);
driver.switchTo().defaultContent();
continue;
}
try {
try{
iFramePwd = driver.findElement(By.cssSelector("input[type='password']"));
}
catch(NoSuchElementException lkn){
System.out.println(lkn);
driver.switchTo().defaultContent();
continue;
}
Size of iframes displaying as 5 but when i try to switch to the iFrame iam always getting NoSuchFrameException.
Please visit the specified URL for analyzing the source code. I dont know where i am missing the point. Is there any way to get password field from the modal window. Any help would be greatly appreciated. Thanks in advance
Try this code
WebDriver driver = new FirefoxDriver();
driver.get("http://imgur.com/");
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.findElement(By.partialLinkText("sign in")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.className("cboxIframe")));
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("f")));
driver.findElement(By.name("username")).sendKeys("abcd");
driver.findElement(By.xpath(".//*[#id='password']/input")).sendKeys("abcd");
driver.close();
driver.quit();
If we use loop to reach the iframe, there is a problem. You don't know which ifrmae you are in because List of web elements does not grantee the exact sequence of iframe in page. For Example below code is not working and showing error "Element belongs to a different frame than the current one - switch to its containing frame to use it"
List<WebElement> my_iframes = driver.findElements(By.tagName("iframe"));
// moving to inner iframe
if(my_iframes.size() > 0){
for(WebElement my_iframe : my_iframes){
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(my_iframe));
}
}
driver.findElement(By.name("username")).sendKeys("abcd");
driver.findElement(By.xpath(".//*[#id='password']/input")).sendKeys("abcd");

Categories