Mouse hover action is not highlighting the element - selenium

Problem : Mouse hover action is not highlighting the element . We are using selenium's mousehover() method.
What we tried : We tried the three solutions given in http://toolsqa.com/selenium-webdriver/mouse-hover-action/ link but none of it worked to achieve the goal.
Please let us know your advise or suggestion for achieving this.

which browser you are using because if you are using firefox and selenium 3.5 there is an issue regarding mouse actions which they are looking into it. I suggest try running it in chrome and check

Try JavaScript for mouse hover. Please give below code try and let me know if its works:
string javaScript = "var evObj = document.createEvent('MouseEvents');" +
"evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" +
"arguments[0].dispatchEvent(evObj);";
JavascriptExecutor js = = (JavascriptExecutor)driver;
//Pass element on which mouse hover to be performed
js.executeScript(javaScript,element)
Pass you webelement in above line on which you want to perform mouse hover.

Related

Text highlight with mouse actions in selenium with java not working

Using selenium and java, I need to highlight the below text using a mouse click and move, After highlighting, the text I can see another popup and I need to do some validation on that popup.
<h2 class="lstw">16.1 This is sample text, another, and heading</h2>
This is my current code and it is not working sometimes. Please note KeyDown or set CSS through javascript is cannot use here.
public boolean userMoveHighlightText(String text){
String secName = "//h2[text()='"+text+"']";
getFrame(); // switch to iframe
By element = getLocator(secName, BY_TYPE.BY_XPATH);
Actions action = new Actions(getWebDriver());
WebElement content = $(element);
action.moveToElement(content, 0, 0).clickAndHold().moveToElement(content, content.getSize().getWidth() / 2, content.getSize().getHeight() / 2);
action.release().build().perform();
return true;
}
Replace the below code with the recommended:
action.moveToElement(content, 0, 0).clickAndHold().moveToElement(content, content.getSize().getWidth() / 2, content.getSize().getHeight() / 2);
Recommended:
action.moveToElement(content, 0, 0).build().perform()
//implicit wait
action.clickAndHold().moveToElement(content, content.getSize().getWidth() / 2, content.getSize().getHeight() / 2).release().build().perform();

How to send right and left cursor using Soda/Selenium?

I'm using Soda to run Selenium Webdriver. Mostly it's working as expected but I'm trying to figure how to send the right and left cursor keys to the browser to move a jquery ui slider handle.
I tried
.typeKeys('css=a.ui-slider-handle[lr="l"]','\37')
and
.type('css=a.ui-slider-handle[lr="l"]','\37')
and
.typeKeys('\37')
and
.type('\37')
Nothing seems to move the slider. None of them error either. I'm sending a click to the handle before I do this just to be sure...
Anyone know how to do this?
Working code in Java-
WebDriver driver = new InternetExplorerDriver();
driver.get("http://jqueryui.com/demos/slider/");
//Identify WebElement
WebElement slider = driver.findElement(By.xpath("//div[#id='slider']/a"));
//Using Action Class
Actions move = new Actions(driver);
Action action = move.dragAndDropBy(slider, 30, 0).build();
action.perform();
driver.quit();
Source - https://gist.github.com/2497551
Try below, I tested this in firefox with jquery UI slider page and it worked for me.
.clickAt("//div[#id='slider']/a[1]", "")
//mouse left key down
.mouseDownAt("//div[#id='slider']/a[1]", "0,0")
//move the cursor some 200 from left
.mouseMoveAt("//div[#id='slider']", "200,0")
//Release the mouse button
.mouseUpAt("//div[#id='slider']", "");

Selenium IDE testing on maps(Open Layers)

I am working on testing an application with open layers maps using Selenium IDE. I researched a lot about clicking on the specific point on the map but I couldn't do it. Can you please provide me some start on this.
Thanks in advance.
Regards,
Rakesh
if you don't want to change the open layers code from Selenium IDE you can run your own javaScript functions by using "runScript" as a command and write your javaScript code into the target field (don't use comments as everything is written in one line).
use the following script to fire a mousedown, mouseup and if you need a click event on the map:
var mousedownEvent = document.createEvent('MouseEvents');
mousedownEvent.initMouseEvent('mousedown', true, true, window, 0, 0, 0, yourX, yourY, false, false, false, false, 0, null);
// creates an element from where the clickEvent can be fired
// instead of using pixel you can also refer to your dom-Element by id
document.elementFromPoint(16,118).dispatchEvent(mousedownEvent);
var mouseupEvent = document.createEvent('MouseEvents');
mouseupEvent.initMouseEvent('mouseup', true, true, window, 0, 0, 0, yourX, yourY, false, false, false, false, 0, null);
// same element
document.elementFromPoint(16,118).dispatchEvent(mouseupEvent);
// in some cases a click event needs to be fired as well

How to do right click in selenium test

I have using recursiveTreeNodesAdaptor in seam. And I want to add child this tree via contextMenu and when user click right node of tree open context menu and click left then open modal panel. I want to do this.
When I try to write selenium test this flow I dont click to rigt and open contextMenu. I try to selenium.contextmenu(xpath) but i'm fail.
So, How can I click to right
I tried to simulate right click with user extension. My function is below:
Selenium.prototype.doContextMenuClick = function(element){
var evt = document.createEvent('MouseEvents');
var RIGHT_CLICK_BUTTON_CODE = 2; // the same for FF and IE
evt.initMouseEvent('contextmenu', true, true,
document.defaultView, 1, 0, 0, 0, 0, false,
false, false, false, RIGHT_CLICK_BUTTON_CODE, null);
if (document.createEventObject){
// dispatch for IE
return document.fireEvent('onclick', evt);
}
else{
// dispatch for firefox + others
return !document.dispatchEvent(evt);
}};
I managed to call the function from IDE. But, now, I get the error "this.waitForCondition is not a function". What's wrong? Do you have any idea?
Thanks in advance.
Try using fireEvent on that element.
You should also take a look at this post which seems to be about the same issue.
The latest selenium has a namespace called OpenQA.Selenium.Interactions Namespace. check it out here.
see my other post here

Clicking at coordinates without identifying element

As part of my Selenium test for a login function, I would like to click a button by identifying its coordinates and instructing Selenium to click at those coordinates. This would be done without identifying the element itself (via id, xpath, etc).
I understand there are other more efficient ways to run a click command, but I'm looking to specifically use this approach to best match the user experience. Thanks.
There is a way to do this. Using the ActionChains API you can move the mouse over a containing element, adjust by some offset (relative to the middle of that element) to put the "cursor" over the desired button (or other element), and then click at that location. Here's how to do it using webdriver in Python:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Chrome()
elem = browser.find_element_by_selector(".some > selector")
ac = ActionChains(browser)
ac.move_to_element(elem).move_by_offset(x_offset, y_offset).click().perform()
Y'all are much to quick to dismiss the question. There are a number of reasons one might to need to click at a specific location, rather than on an element. In my case I have an SVG bar chart with an overlay element that catches all the clicks. I want to simulate a click over one of the bars, but since the overlay is there Selenium can't click on the element itself. This technique would also be valuable for imagemaps.
In C# API you use actions
var element = driver.FindElement(By...);
new Actions(driver).moveToElement(element).moveByOffset(dx, dy).click().perform();
Although it is best to just use simple Id, CSS, Xpath selectors when possible. But the functionality is there when needed (i.e. clicking elements in certain geographic places for functionality).
I first used the JavaScript code, it worked amazingly until a website did not click.
So I've found this solution:
First, import ActionChains for Python & active it:
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
To click on a specific point in your sessions use this:
actions.move_by_offset(X coordinates, Y coordinates).click().perform()
NOTE: The code above will only work if the mouse has not been touched, to reset the mouse coordinates use this:
actions.move_to_element_with_offset(driver.find_element_by_tag_name('body'), 0,0))
In Full:
actions.move_to_element_with_offset(driver.find_element_by_tag_name('body'), 0,0)
actions.move_by_offset(X coordinates, Y coordinates).click().perform()
This can be done using Actions class in java
Use following code -
new Actions(driver).moveByOffset(x coordinate, y coordinate).click().build().perform();
Note: Selenium 3 doesn't support Actions class for geckodriver
Also, note that x and y co-ordinates are relative values from current mouse position. Assuming mouse co-ordinates are at (0,0) to start with, if you want to use absolute values, you can perform the below action immediately after you clicked on it using the above code.
new Actions(driver).moveByOffset(-x coordinate, -y coordinate).perform();
If using a commercial add-on to Selenium is an option for you, this is possible: Suppose your button is at coordinates x=123, y=456. Then you can use Helium to click on the element at these coordinates as follows:
from helium.api import *
# Tell Helium about your WebDriver instance:
set_driver(driver)
click(Point(123, 456))
(I am one of Helium's authors.)
This worked for me in Java for clicking on coordinates irrespective on any elements.
Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.tagName("body")), 0, 0);
actions.moveByOffset(xCoordinate, yCoordinate).click().build().perform();
Second line of code will reset your cursor to the top left corner of the browser view and last line will click on the x,y coordinates provided as parameter.
In Selenium Java, you can try it using Javascript:
WebDriver driver = new ChromeDriver();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor) driver).executeScript("el = document.elementFromPoint(x-cordinate, y-cordinate); el.click();");
}
Action chains can be a little finicky. You could also achieve this by executing javascript.
self.driver.execute_script('el = document.elementFromPoint(440, 120); el.click();')
I used the Actions Class like many listed above, but what I found helpful was if I need find a relative position from the element I used Firefox Add-On Measurit to get the relative coordinates.
For example:
IWebDriver driver = new FirefoxDriver();
driver.Url = #"https://scm.commerceinterface.com/accounts/login/?next=/remittance_center/";
var target = driver.FindElement(By.Id("loginAsEU"));
Actions builder = new Actions(driver);
builder.MoveToElement(target , -375 , -436).Click().Build().Perform();
I got the -375, -436 from clicking on an element and then dragging backwards until I reached the point I needed to click. The coordinates that MeasureIT said I just subtracted. In my example above, the only element I had on the page that was clickable was the "loginAsEu" link. So I started from there.
If all other methods mentioned on this page failed and you are using python, I suggest you use the mouse module to do it in a more native way instead. The code would be as simple as
import mouse
mouse.move("547", "508")
mouse.click(button='left')
You can also use the keyboard module to simulate keyboard actions
import keyboard
keyboard.write('The quick brown fox jumps over the lazy dog.')
To find the coordinate of the mouse, you can use the follow JavaScript Code.
document.onclick=function(event) {
var x = event.screenX ;
var y = event.screenY;
console.log(x, y)
}
If you don't like screenX, you can use pageX or clientX. More on here
P.S. I come across a website that prevents programmatic interactions with JavaScript/DOM/Selenium. This is probably a robot prevention mechanism. However, there is no way for them to ban OS actions.
WebElement button = driver.findElement(By.xpath("//button[#type='submit']"));
int height = button.getSize().getHeight();
int width = button.getSize().getWidth();
Actions act = new Actions(driver);
act.moveToElement(button).moveByOffset((width/2)+2,(height/2)+2).click();
import pyautogui
from selenium import webdriver
driver = webdriver.Chrome(chrome_options=options)
driver.maximize_window() #maximize the browser window
driver.implicitly_wait(30)
driver.get(url)
height=driver.get_window_size()['height']
#get browser navigation panel height
browser_navigation_panel_height = driver.execute_script('return window.outerHeight - window.innerHeight;')
act_y=y%height
scroll_Y=y/height
#scroll down page until y_off is visible
try:
driver.execute_script("window.scrollTo(0, "+str(scroll_Y*height)+")")
except Exception as e:
print "Exception"
#pyautogui used to generate click by passing x,y coordinates
pyautogui.FAILSAFE=False
pyautogui.moveTo(x,act_y+browser_navigation_panel_height)
pyautogui.click(x,act_y+browser_navigation_panel_height,clicks=1,interval=0.0,button="left")
This is worked for me. Hope, It will work for you guys :)...
I used AutoIt to do it.
using AutoIt;
AutoItX.MouseClick("LEFT",150,150,1,0);//1: click once, 0: Move instantaneous
Pro:
simple
regardless of mouse movement
Con:
since coordinate is screen-based, there should be some caution if the app scales.
the drive won't know when the app finish with clicking consequence actions. There should be a waiting period.
To add to this because I was struggling with this for a while. These are the steps I took:
Find the coordinates you need to click. Use the code below in your console and it will display and alert of the coordinates you need.
document.onclick = function(e)
{
var x = e.pageX;
var y = e.pageY;
alert("User clicked at position (" + x + "," + y + ")")
};
Make sure the element is actually visible on the screen and click it using Actionchains
WebDriverWait(DRIVER GOES HERE, 10).until(EC.element_to_be_clickable(YOUR ELEMENT LOCATOR GOES HERE))
actions = ActionChains(DRIVER GOES HERE)
actions.move_by_offset(X, Y).click().perform()
Selenium::WebDriver has PointerActions module which includes a number of actions you can chain and/or trigger without specifying the element, eg. move_to_location or move_by. See detailed specs here. As you can see, you can only use actual coordinates. I am sure this interface is implemented in other languages / libraries accordingly.
My short reply may echo some other comments here, but I just wanted to provide a link for reference.
You could use the html tag as the element and then use the coordinates you want, in this example below I am using Javascript. But I am able to click on the top left of the screen.
async function clickOnTopLeft() {
const html = driver.wait(
until.elementLocated(By.xpath('/html')),
10000)
const { width, height } = await html.getRect()
const offSetX = - Math.floor(width / 2)
const offsetY = - Math.floor(height / 2)
await driver.actions().move(
{ origin: html, x: offSetX, y: offsetY })
.click().perform()
}
If you can see the source code of page, its always the best option to refer to the button by its id or NAME attribute. For example you have button "Login" looking like this:
<input type="submit" name="login" id="login" />
In that case is best way to do
selenium.click(id="login");
Just out of the curiosity - isnt that HTTP basic authentification? In that case maybe look at this:
http://code.google.com/p/selenium/issues/detail?id=34
Selenium won't let you do this.