how can you do right click using selenium? - selenium

im trying to preform a right click using selenium, any thoughts on how to do this?

According to the OpenQA.Selenium.Interactions Namespace.
// step 1 - select the element you want to right-click
var elementToRightClick = this.Driver.FindElement(By.Id("elementtoclickonhasthisid"));
// step 2 - create and step up an Actions object with your driver
var action = new OpenQA.Selenium.Interactions.Actions(this.Driver);
action.ContextClick(elementToRightClick);
// step 3 - execute the action
action.Perform();

Please see docroots's answer for selenium.
To generally simulate a right click in JavaScript, have a look at JavaScript simulate right click through code.

it appears that for my issue (an element that opens a popup after a right click), using selenium's : mouse_down_right() and then mouse_up_right()
worked as well. thanks.

Selenium is offering a method for right click - ContextClick:
public void RightClick(IWebElement target)
{
var builder = new Actions(driver);
builder.ContextClick(target);
builder.Perform();
}

I've tried ActionSequence and it worked.
ContextClick function is not found, you should use click.
So, it should be as follows:
driver.actions().click(element,2).perform();
The element is your web element, 2 means right click.

Related

Selenium: Click and Hold the element and then Slide it

In my application I have a scenario where I need to slide an element in list view to add new entry to the item. I have to automate it using Selenium and C#. Application is developed using Ionic and Angular Frameworks.
In Selenium there is an option to ClickAndHold and MoveByOffset methods but none of these seems to be working. At the same time no errors are displayed. Please help.
Code I have tried so far is as below.
Actions dragger = new Actions(driver);
elementToSlide = driver.FindElement(By.XPath("//ion-item-slide[1]"));
dragger.ClickAndHold(elementToSlide).MoveByOffset(-47,0).Build().Perform();
Images are attached for reference. The first element in the list view slides.
Maybe the drag and drop command could solve your problem,try like this
IWebElement elementToSlide = driver.FindElement(By.XPath("//ion-item-slide[1]"))
Actions dragger = new Actions(driver);
dragger.DragAndDropToOffset(elementToSlide, -47, 0).Build().Perform();
I had the same problem, I wrote the code like this and it worked for me:
Actions action = new Actions(driver);
action.clickAndHold(elementToSlide);
action.moveToElement(NextplaceElement).release();
action.build().perform();
Thanks for your answers, actually I figured out in ionic framework we should not use ion-item-sliding element for sliding, but the next child which is ion-item. I did by using the following code.
var slidableItm = driver.FindElement(By.XPath("//ion-item-sliding/ion-item");
Actions dragger = new Actions(driver);
dragger.ClickAndHold(slidableItm))).MoveByOffset(-47, 0).Build().Perform();
Then after sliding we need to click on some element's coordinates to complete and release the slide. It can be achieved by following code.
var clickableItm = driver.FindElement(By.XPath("/ion-item-sliding/ion-item/div[1]/div/ion-label/div/p[1]"));
ILocatable c = (ILocatable)clickableItm;
RemoteWebDriver rd = (RemoteWebDriver)driver;
rd.Mouse.Click(c.Coordinates);
Actions a = new Actions(driver);
a.clickAndHold(e2).pause(2000).moveToElement(e1).release().build().perform();

Click on the element which is visible after mouse hovering

I have to click on a tile which is generated after mouse hovering. I wrote the code below but it is still not working.
WebElement FrontElement=driver.findElement(By.xpath("//a[#class='sol-itm-bx relative front-app-nm']/span[text()='UI Auto Test12345']"));
WebElement BackElement= driver.findElement(By.xpath("//a[#class='relative back-app-desc']/span[text()='UI Auto Test12345']"));
Actions builder = new Actions(driver);
builder.moveToElement(FrontElement);
builder.perform();
builder.clickAndHold(FrontElement);
BackElement.click();
To use the Actions() class you need to chain the actions together. Separate commands won't work in the way you want.
Actions builder = new Actions(driver);
builder.moveToElement(driver.findElement(By.xpath("//a[#class='sol-itm-bx relative front-app-nm']/span[text()='UI Auto Test12345']")))
.moveToElement(driver.findElement(By.xpath("//a[#class='relative back-app-desc']/span[text()='UI Auto Test12345']")))
.click().perform();
Note: I've separated the lines for ease of reading.
EDIT: 'build' to 'builder' NullPointerException

Switching to a window with no name

Using the Codeception testing framework and Selenium 2 module to test a website, I end up following a hyperlink that opens a new window with no name. As a result the switchToWindow() function will not work because it is trying to switch to the parent window (which I'm currently on). Without being able to switch to the new window I cannot perform any testing on it.
<a class="external" target="_blank" href="http://mylocalurl/the/page/im/opening">
View Live
</a>
Using both Chrome and Firefox debugging tools I can confirm the new window doesn't have a name, and I cannot give it one because I cannot edit the HTML page I am working on. Ideally I would have changed the HTML to use javascript onclick="window.open('http://mylocalurl/the/page/im/opening', 'myPopupWindow') however this is not possible in my case.
I've looked around on the Selenium forums without any clear method to tackle this problem, and Codeception doesn't appear to have much functionality around this.
After searching around on the Selenium forum and some helpful prods from #Mark Rowlands, I got it to work using raw Selenium.
// before codeception v2.1.1, just typehint on \Webdriver
$I->executeInSelenium(function (\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) {
$handles=$webdriver->window_handles();
$last_window = end($handles);
$webdriver->focusWindow($last_window);
});
Returning back to the parent window was easy because I could just use Codeception's switchToWindow method:
$I->switchToWindow();
Building on the accepted answer, in Codeception 2.2.9 I was able to add this code to the Acceptance Helper and it seems to work.
/**
* #throws \Codeception\Exception\ModuleException
*/
public function switchToNewWindow()
{
$webdriver = $this->getModule('WebDriver')->webDriver;
$handles = $webdriver->getWindowHandles();
$lastWindow = end($handles);
$webdriver->switchTo()->window($lastWindow);
}
Then in the test class I can do this:
$I->click('#somelink');
$I->switchToNewWindow();
// Some assertions...
$I->switchToWindow(); // this switches back to the previous window
I had a heck of a time trying to figure out how to do this by just searching google, so I hope it helps someone else.
Try this,
String parentWindowHandle = browser.getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Iterator<String> windowIterator = browser.getWindowHandles();
while(windowIterator.hasNext()) {
String windowHandle = windowIterator.next();
popup = browser.switchTo().window(windowHandle);
}
make sure to return on parent window using,
browser.close(); // close the popup.
browser.switchTo().window(parentWindowHandle); // Switch back to parent window.
I hope will help you.
Using Codeception 2.2+ it looks like this:
$I->executeInSelenium(function (\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) {
$handles = $webdriver->getWindowHandles();
$lastWindow = end($handles);
$webdriver->switchTo()->window($lastWindow);
});

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']", "");

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.