Getting value from tooltip when hover on svg element on the graph created with highcharts - selenium

I want to get text/value from the tooltip which appears when hover on svg element on the graph created with highcharts.
Below is the snippet:
Tried below code:
List<WebElement> Volumelist=driver.findElements(By.xpath("//*[name()='svg']//*[name()='g'][5]//*[name()='g'][2]//*[name()='path']"));
System.out.println("Got the list!");
new Actions(driver).moveToElement(Volumelist.get(1)).clickAndHold().build().perform();
WebElement toolTip=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#class='highcharts-halo highcharts-color-3'][#visibility='visible']")));
System.out.println("toolTip text= "+toolTip.getText());

First hover on the element on which tooltip appears and then execute :
String tooltipText = driver.findElement(By.cssSelector("g.highcharts-tooltip text tspan")).getAttribute("textContent");
You can ping me at sandpdangi13#gmail.com if that does not work for you.
Try to hover to tooltip element using this method if normal Actions hover is not working :
public static void mouseHoverJScript(WebDriver driver, WebElement element) {
String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false);"
+ " arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
((JavascriptExecutor) driver).executeScript(mouseOverScript,
element);

I found over their examples page the values with this XPath:
driver.findElement(By.xpath(.//*[name()="g" and contains(#class,"highcharts-label")]//*[name()="tspan" and #style='font-weight:bold'])).getText();
The first step is move the mouse over one point, for example with this XPath, move to the first point:
WebElement elem = DriverUtils.driver.findElement(By.xpath(.//*[name()='path' and contains(#class, 'highcharts-point highcharts-color')][1]));
new Actions(driver).moveToElement(elem).clickAndHold().build().perform();
I used the Selenium 3.9.0, with previous 3.4.0 version doesn't work for me.

So, solution that worked for me:
WebElement elem = driver.findElement(By.xpath("//[name()='svg']//[name()='g'][5]//[name()='g'][2]//[name()='path'][1]"));
new Actions(driver).moveToElement(elem).clickAndHold().moveByOffset(1, 1).pause(1000).perform();
String text=driver.findElement(By.xpath("//[name()='svg']//[name()='g'][9]//[name()='text'][1]//[name()='tspan'][3]")).getText();

Related

How to click a button created using <span> tag for Selenium webdriver?

I have span tag which looks like a button on html tag
<span class="middle">Next</span>
I tried using
xpath=driver.findElement(By.xpath(".//*[#id='modal-actions-panel']/div[2]/a/span/span/span")); // by considering fixed id as reference
Using absolute
xpath=driver.findElement(By.xpath("html/body/div[4]/div[2]/a/span/span/span")); // took this from firebug
and Using
driver.findElement(By.cssSelector("span[class='middle']"));
No success!! It is throwing below exception :
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//span[contains(., \"Next\")]"}
Command duration or timeout: 30.12 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
For all the ways I tried it is showing the same exception with change in selector details. Can someone please help me out in finding solution so that I can find Next button that is in span tag and click it.
Next button is in iFrame: Below is the part of html covering required span tag.
Next
I also tried with :
driver.switchTo().frame("iframe-applicationname_ModalDialog_0");
WebElement el = driver.findElement(By.cssSelector("span.middle"));
But throwing below error :
Caused by: org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with
Kindly let me know if needed something that I'm missing..
I think this element is inside a frame or iframe, if it is then you need to switch that frame or iframe before finding element as below :-
driver.switchTo().frame("iframe-applicationname_ModalDialog_0");
WebElement el = driver.findElement(By.cssSelector("span.middle"));
el.click();
//Now after all your stuff done inside frame need to switch to default content
driver.switchTo().defaultContent();
Edited1 :- If you are getting exception as element is not currently visible need to implement WebDriverWait to wait until element visible as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
//Find frame or iframe and switch
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("iframe-applicationname_ModalDialog_0"));
//Now find the element
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//span[#class = 'middle' and contains(text(), 'Next')]")));
el.click();
//Once all your stuff done with this frame need to switch back to default
driver.switchTo().defaultContent();
Edited2 :- If unfortunately it's not getting visible try to click on it using JavascriptExecutor as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
//Find frame or iframe and switch
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("iframe-applicationname_ModalDialog_0"));
//Now find the element
WebElement el = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//span[#class = 'middle' and contains(text(), 'Next')]")));
//Now click using JavascriptExecutor
((JavascriptExecutor)driver).executeScript("arguments[0].click()" el);
//Once all your stuff done with this frame need to switch back to default
driver.switchTo().defaultContent();
Try this....
driver.findElement(By.xpath("//span[contains(#class,'middle') and contains(text(), 'Next')]"))
I tried it and it worked for me:
WebElement actionBtn=driver2.findElement(
By.xpath("//span[contains(#class,'v-menubar-menuitem-caption')
and contains(text(), 'Actions')]")
);
actionBtn.click();
Try this
new WebDriverWait(driver, 30).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(#class,'middle') and contains(text(), 'Next')]"))).click();

Selenium click not work

Help me please.
Selenium does not click on element and element is clickable(selenium does not generate exception).
I try use Id, css, xpath locators, nothing did not help me.
What should i do to decide my problem?
Java code example.
WebElement sector = webDriver.findElement(By.id("sector-1"));
sector.click();
After click system must open this page
Seems that you try to interact with object inside a <svg> element. If so, you cannot manage it's child elements simply using click() method.
Try this instead:
WebElement svgObject = driver.findElement(By.xpath("//polygon[#id='sector-1:canvas']"));
Actions builder = new Actions(driver);
builder.click(svgObject).build().perform();
Use below XPath :
WebElement sector = webDriver.findElement(By.xpath("//g[#id='sector-1']/polygon"));
sector.click();
OR
WebElement sector = webDriver.findElement(By.xpath("//polygon[#id='sector-1:canvas']"));
sector.click();
I decide my problem.
WebDriverWait wait = new WebDriverWait(webDriver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"sector-2:canvas\"]")));
WebElement svgObject = webDriver.findElement(By.xpath("//*[#id=\"sector-2:canvas\"]"));
Actions builder = new Actions(webDriver);
builder.click(svgObject).build().perform();

Modify innerHTML using Selenium

I have this element:
WebElement element = ...
string val = element.getAttribute("innerHTML");
All I want to do is to change this innerHTML on my web page.
Is it possible?
Try this:
WebElement element = ...
((JavascriptExecutor)driver).executeScript(
"var ele=arguments[0]; ele.innerHTML = 'my new content';", element);
Selenium WebDriver does not have any direct methods to do so to change the DOM itself. However we can use JavascriptExecutor to use javascript to modify the DOM.
check this example to change the background color. You will get an idea to change the innerHTML as well.
in python use this :
element = driver.find_element_by_id("some_id")
driver.execute_script("arguments[0].innerText = 'what_you_want_to_show'", element)

How to get a tooltip text on mouseover using Selenium WebDriver

I am not able to get tooltip text after mouseover on icon tooltip. I need to get tooltip text,This is html code.
<a class="tooltip" onclick="SocialAuth.showOpenIDLoginWindow('google');_gaq.push(['_trackEvent','LoginForm','google-login','google login was clicked']);" href="javascript:void(0);"><span>We dont store your password or access your contacts on your Google account.</span><img class="social" height="39" width="40" src="/images/login/google.png"/>
The method to get text from a tool tip differs from a HTML one when its a Jquery ToolTip.
getAttribute() does not work when its a Jquery ToolTip. If you see the tooltip example at http://demoqa.com/tooltip/ , its a jquery tooltip.
Following code works here:
WebDriver driver=new FirefoxDriver();
driver.get("http://demoqa.com/tooltip/");
WebElement element = driver.findElement(By.xpath(".//*[#id='age']"));
Actions toolAct = new Actions(driver);
toolAct.moveToElement(element).build().perform();
WebElement toolTipElement = driver.findElement(By.cssSelector(".ui-tooltip"));
String toolTipText = toolTipElement.getText();
System.out.println(toolTipText);
A good reference is:
http://www.seleniumeasy.com/selenium-tutorials/how-to-verify-tooltip-text-with-selenium-webdriver-using-java
Use the below line of code for fetching the tool tip text from the Element.
String toolTipText = driver.findElement(By.id(element's id)).getAttribute("title");
You have to use Actions for this. in this am printing the mouse hover message in Google
Actions ToolTip1 = new Actions(driver);
WebElement googleLogo = driver.findElement(By.xpath("//div[#id='hplogo']"));
Thread.sleep(2000);
ToolTip1.clickAndHold(googleLogo).perform();
Perform mouse hover action using 'clickAndHold' method.
Get the value of Tool tip by using 'getAttribute' command
String ToolTipText = googleLogo.getAttribute("title");
Assert.assertEquals(ToolTipText, "Google");
Thread.sleep(2000);
System.out.println("Tooltip value is: " + ToolTipText);

Scroll Element into View with Selenium

Is there any way in either Selenium 1.x or 2.x to scroll the browser window so that a particular element identified by an XPath is in view of the browser? There is a focus method in Selenium, but it does not seem to physically scroll the view in FireFox. Does anyone have any suggestions on how to do this?
The reason I need this is I'm testing the click of an element on the page. Unfortunately the event doesn't seem to work unless the element is visible. I don't have control of the code that fires when the element is clicked, so I can't debug or make modifications to it, so, easiest solution is to scroll the item into view.
Have tried many things with respect to scroll, but the below code has provided better results.
This will scroll until the element is in view:
WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
//do anything you want with the element
You can use the org.openqa.selenium.interactions.Actions class to move to an element.
Java:
WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();
Python:
from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).move_to_element(driver.sl.find_element_by_id('my-id')).perform()
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:window.scrollBy(250,350)");
You may want to try this.
If you want to scroll on the Firefox window using the Selenium webdriver, one of the ways is to use JavaScript in the Java code. The JavaScript code to scroll down (to bottom of the web page) is as follows:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight));");
Targeting any element and sending down keys (or up/left/right) seems to work also. I know this is a bit of a hack, but I'm not really into the idea of using JavaScript to solve the scrolling problem either.
For example:
WebElement.sendKeys(Keys.DOWN);
In Selenium we need to take the help of a JavaScript executor to scroll to an element or scroll the page:
je.executeScript("arguments[0].scrollIntoView(true);", element);
In the above statement element is the exact element where we need to scroll. I tried the above code, and it worked for me.
I have a complete post and video on this:
http://learn-automation.com/how-to-scroll-into-view-in-selenium-webdriver/
webElement = driver.findElement(By.xpath("bla-bla-bla"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", webElement);
For more examples, go here. All in Russian, but Java code is cross-cultural :)
I found that the bounding rect of my element was not correct, leading to the browser scrolling well off the screen. However, the following code works rather well for me:
private void scrollToElement(WebElement webElement) throws Exception {
((JavascriptExecutor)webDriver).executeScript("arguments[0].scrollIntoViewIfNeeded()", webElement);
Thread.sleep(500);
}
You can use this code snippet to scroll:
C#
var element = Driver.FindElement(By.Id("element-id"));
Actions actions = new Actions(Driver);
actions.MoveToElement(element).Perform();
There you have it
This worked for me:
IWebElement element = driver.FindElements(getApplicationObject(currentObjectName, currentObjectType, currentObjectUniqueId))[0];
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
Use the driver to send keys like the pagedown or downarrow key to bring the element into view. I know it's too simple a solution and might not be applicable in all cases.
From my experience, Selenium Webdriver doesn't auto scroll to an element on click when there are more than one scrollable section on the page (which is quite common).
I am using Ruby, and for my AUT, I had to monkey patch the click method as follows;
class Element
#
# Alias the original click method to use later on
#
alias_method :base_click, :click
# Override the base click method to scroll into view if the element is not visible
# and then retry click
#
def click
begin
base_click
rescue Selenium::WebDriver::Error::ElementNotVisibleError
location_once_scrolled_into_view
base_click
end
end
The 'location_once_scrolled_into_view' method is an existing method on WebElement class.
I apreciate you may not be using Ruby but it should give you some ideas.
The Ruby script for scrolling an element into view is as below.
$driver.execute_script("arguments[0].scrollIntoView(true);", element)
sleep(3)
element.click
Selenium 2 tries to scroll to the element and then click on it. This is because Selenium 2 will not interact with an element unless it thinks that it is visible.
Scrolling to the element happens implicitly so you just need to find the item and then work with it.
Sometimes I also faced the problem of scrolling with Selenium. So I used javaScriptExecuter to achieve this.
For scrolling down:
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollBy(0, 250)", "");
Or, also
js.executeScript("scroll(0, 250);");
For scrolling up:
js.executeScript("window.scrollBy(0,-250)", "");
Or,
js.executeScript("scroll(0, -250);");
This is a repeated solution with JavaScript, but with an added waiting for element.
Otherwise ElementNotVisibleException may appear if some action on the element is being done.
this.executeJavaScriptFunction("arguments[0].scrollIntoView(true);", elementToBeViewable);
WebDriverWait wait = new WebDriverWait(getDriver(), 5);
wait.until(ExpectedConditions.visibilityOf(elementToBeViewable));
I have used this way for scrolling the element and click:
List<WebElement> image = state.getDriver().findElements(By.xpath("//*[contains(#src,'image/plus_btn.jpg')]"));
for (WebElement clickimg : image)
{
((JavascriptExecutor) state.getDriver()).executeScript("arguments[0].scrollIntoView(false);", clickimg);
clickimg.click();
}
def scrollToElement(element: WebElement) = {
val location = element.getLocation
driver.asInstanceOf[JavascriptExecutor].executeScript(s"window.scrollTo(${location.getX},${location.getY});")
}
Something that worked for me was to use the Browser.MoveMouseToElement method on an element at the bottom of the browser window. Miraculously it worked in Internet Explorer, Firefox, and Chrome.
I chose this over the JavaScript injection technique just because it felt less hacky.
You may want to visit page Scroll Web elements and Web page- Selenium WebDriver using Javascript:
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FirefoxDriver ff = new FirefoxDriver();
ff.get("http://toolsqa.com");
Thread.sleep(5000);
ff.executeScript("document.getElementById('text-8').scrollIntoView(true);");
}
If you think other answers were too hacky, this one is too, but there is no JavaScript injection involved.
When the button is off the screen, it breaks and scrolls to it, so retry it... ¯\_(ツ)_/¯
try
{
element.Click();
}
catch {
element.Click();
}
In most of the situation for scrolling this code will work.
WebElement element = driver.findElement(By.xpath("xpath_Of_Element"));
js.executeScript("arguments[0].click();",element);
JAVA
Try scroll to element utilize x y position, and use JavascriptExecutor with this is argument: "window.scrollBy(x, y)".
Following import:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
First you need get x y location the element.
//initialize element
WebElement element = driver.findElement(By.id("..."));
//get position
int x = element.getLocation().getX();
int y = element.getLocation().getY();
//scroll to x y
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(" +x +", " +y +")");
I am not sure if the question is still relevant but after referring to scrollIntoView documentation from https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView.
The easiest solution would be
executor.executeScript("arguments[0].scrollIntoView({block: \"center\",inline: \"center\",behavior: \"smooth\"});",element);
This scrolls the element into center of the page.
Javascript
The solustion is simple:
const element = await driver.findElement(...)
await driver.executeScript("arguments[0].scrollIntoView(true);", element)
await driver.sleep(500);
The default behavior of Selenium us to scroll so the element is barely in view at the top of the viewport. Also, not all browsers have the exact same behavior. This is very dis-satisfying. If you record videos of your browser tests, like I do, what you want is for the element to scroll into view and be vertically centered.
Here is my solution for Java:
public List<String> getBoundedRectangleOfElement(WebElement we)
{
JavascriptExecutor je = (JavascriptExecutor) driver;
List<String> bounds = (ArrayList<String>) je.executeScript(
"var rect = arguments[0].getBoundingClientRect();" +
"return [ '' + parseInt(rect.left), '' + parseInt(rect.top), '' + parseInt(rect.width), '' + parseInt(rect.height) ]", we);
System.out.println("top: " + bounds.get(1));
return bounds;
}
And then, to scroll, you call it like this:
public void scrollToElementAndCenterVertically(WebElement we)
{
List<String> bounds = getBoundedRectangleOfElement(we);
Long totalInnerPageHeight = getViewPortHeight(driver);
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("window.scrollTo(0, " + (Integer.parseInt(bounds.get(1)) - (totalInnerPageHeight/2)) + ");");
je.executeScript("arguments[0].style.outline = \"thick solid #0000FF\";", we);
}
I've been doing testing with ADF components and you have to have a separate command for scrolling if lazy loading is used. If the object is not loaded and you attempt to find it using Selenium, Selenium will throw an element-not-found exception.
If nothing works, try this before clicking:
public void mouseHoverJScript(WebElement HoverElement) {
String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
((JavascriptExecutor) driver).executeScript(mouseOverScript, HoverElement);
}
In Java we can scroll by using JavaScript, like in the following code:
driver.getEval("var elm = window.document.getElementById('scrollDiv'); if (elm.scrollHeight > elm.clientHeight){elm.scrollTop = elm.scrollHeight;}");
You can assign a desired value to the "elm.scrollTop" variable.
A solution is:
public void javascriptclick(String element)
{
WebElement webElement = driver.findElement(By.xpath(element));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", webElement);
System.out.println("javascriptclick" + " " + element);
}