Webdriver Click() VS JavaScript Click()

WebDriver click() vs JavaScript click()

Contrarily to what the currently accepted answer suggests, there's nothing specific to PhantomJS when it comes to the difference between having WebDriver do a click and doing it in JavaScript.

The Difference

The essential difference between the two methods is common to all browsers and can be explained pretty simply:

  • WebDriver: When WebDriver does the click, it attempts as best as it can to simulate what happens when a real user uses the browser. Suppose you have an element A which is a button that says "Click me" and an element B which is a div element which is transparent but has its dimensions and zIndex set so that it completely covers A. Then you tell WebDriver to click A. WebDriver will simulate the click so that B receives the click first. Why? Because B covers A, and if a user were to try to click on A, then B would get the event first. Whether or not A would eventually get the click event depends on how B handles the event. At any rate, the behavior with WebDriver in this case is the same as when a real user tries to click on A.

  • JavaScript: Now, suppose you use JavaScript to do A.click(). This method of clicking does not reproduce what really happens when the user tries to click A. JavaScript sends the click event directly to A, and B will not get any event.

Why a JavaScript Click Works When a WebDriver Click Does Not?

As I mentioned above WebDriver will try to simulate as best it can what happens when a real user is using a browser. The fact of the matter is that the DOM can contain elements that a user cannot interact with, and WebDriver won't allow you to click on these element. Besides the overlapping case I mentioned, this also entails that invisible elements cannot be clicked. A common case I see in Stack Overflow questions is someone who is trying to interact with a GUI element that already exists in the DOM but becomes visible only when some other element has been manipulated. This sometimes happens with dropdown menus: you have to first click on the button the brings up the dropdown before a menu item can be selected. If someone tries to click the menu item before the menu is visible, WebDriver will balk and say that the element cannot be manipulated. If the person then tries to do it with JavaScript, it will work because the event is delivered directly to the element, irrespective of visibility.

When Should You Use JavaScript for Clicking?

If you are using Selenium for testing an application, my answer to this question is "almost never". By and large, your Selenium test should reproduce what a user would do with the browser. Taking the example of the drop down menu: a test should click on the button that brings up the drop down first, and then click on the menu item. If there is a problem with the GUI because the button is invisible, or the button fails to show the menu items, or something similar, then your test will fail and you'll have detected the bug. If you use JavaScript to click around, you won't be able to detect these bugs through automated testing.

I say "almost never" because there may be exceptions where it makes sense to use JavaScript. They should be very rare, though.

If you are using Selenium for scraping sites, then it is not as critical to attempt to reproduce user behavior. So using JavaScript to bypass the GUI is less of an issue.

What is the difference between Selenium WebDriver Click and JavascriptExecutor Click

WebDriver click() simulates real user interaction with the UI. I will be performed (in most browsers) by sending a native event to the browser, and it has to be visible in order to click on it. From the docs

...if click() is done by sending a native event (which is the
default on most browsers/platforms)

There are some preconditions for an element to be clicked. The element
must be visible and it must have a height and width greater then 0.

JavaScript click() on the other hand

Executes JavaScript in the context of the currently selected frame or
window.

Regardless if the WebElement is visible or not. This approach misses the idea of user interaction Selenium tries to simulate.

Selenium WebElement.click() vs. Javascript click event

Webdriver utilizes a browser's native support for mapping the DOM element to WebElement object using id/xpath etc.

The JavascriptExecutor.executeScript executes an external script in the context of the currently selected browser window. (similar to an augmented browsing tool like grease monkey, if you ever used),
and in case the script returns any DOM element its converted into WebElement object.

One can also say, the click simulated by WebDriver on a browser is similar to what actual user do as compared to one invoked using javascript.

In reality, with WebDriver not all the events can be automated flawlessly with all the web browsers, in fact with different versions of the same Web browser also. (i.e. different version of IE, FF etc behave differently). Still WebDriver is the near best tool available for this.

Once (~4 years back) on a certain version of IE we observed that we can't send right click or may be hover mouse on generated menu links, so we used js to simulate that, which performed very much browser independent way. so you can now conclude what executing external javascript can be good for.

Also, there are automated web testing frameworks which use javascript for everything instead of browser's native support. e.g. :http://en.wikipedia.org/wiki/Sahi_%28software%29

Ref:

  • http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/JavascriptExecutor.html#executeScript%28java.lang.String,%20java.lang.Object...%29
  • http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/WebDriver.html#findElement%28org.openqa.selenium.By%29

Clicking an element using javascript vs actions vs webdriver?

myWebElement.click();

Actions(driver).click(myWebElement).build().perform();

Both click method and actions class belong to webdriver.Action class is used for emulating complex user gestures(including actions such as Drag and Drop or clicking multiple elements With Control key etc).click method is used to click on the respective webElement(buttons,links etc).Selenium Webdriver uses browser's native support for mapping the DOM element to WebElement object using locators like id/xpath etc.

JavaScriptExecutor is an interface which provides mechanism to execute Javascript through selenium driver. It provides “executescript” & "executeAsyncScript" methods, to run external JavaScript in the context of the currently selected frame or window.In the case of executescript it will return an DOM element which is then converted to WebElement

The click simulated by WebDriver on a browser is similar to what actual user do as compared to one invoked using javascript

Example scenario:

<html>
<body>
<button type = "button" id ="test" style = "display:none"> clickme </button>
</body>
</html>

If you click on the "click me" button using click function in webdriver you will get an org.openqa.selenium.ElementNotVisibleException (Element not visible exception) which is correct as the element is present in the DOM but is not displayed to the user as the css style display:none is set

((JavascriptExecutor)driver).executeScript("$('#test').click();");//or
((JavascriptExecutor)driver).executeScript("document.getElementById('test').click();");

If you use the above javascript/jquery to click on the element then it will click on the button regardless of whether the button was visible or not which is wrong because the end user will not be able to see/click on the button but your script will pass.So the moral is try to use webdriver functions wherever possible instead of using javascript

Hope this helps you.Kindly get back if you have any queries

Selenium WebDriver - Click a Javascript Button

button = driver.find_element_by_link_text('Export to Excel')
button.click()

Explanation :

If the above gives you NoSuchElementException, I would probably suspect this it is in iframe, if it happens to be then in that case you would need to switch to iframe first and continute with this web element.

Code :

wait = WebDriverWait(driver, 10)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "iframe xpath here")))
wait.until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Export to Excel"))).click()

Imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

if this does not work, I would probably ask about your driver configuration. Is it opening browser in full screen ?

How to click an element in Selenium WebDriver using JavaScript?

Executing a click via JavaScript has some behaviors of which you should be aware. If for example, the code bound to the onclick event of your element invokes window.alert(), you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.

// Assume driver is a valid WebDriver instance that
// has been properly instantiated elsewhere.
WebElement element = driver.findElement(By.id("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

You should also note that you might be better off using the click() method of the WebElement interface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.

Selenium webdriver click vs action.click whats the difference?

I am not sure about your specific case, but there are several differences between WebElement click method and Actions click method. Actions' click is a lot dumber, it pretty much just sends the click event to the element (location) that you pass in. It does not care about the element, it just does the click and moves forward whereas webelement click is a blocking call (not always, check the references) and it also has preconditions like the WebElement to be clicked must be visible. Also, webElements' click is a void method, actions click returns reference to the Actions you are using. For more information check here and here.


edit.
Looking at the markup you posted, and it can be totally wrong as I am not a boss on bootstrap CSS, the modal hide fade in and especially the fade in part there looks suspicious. Are you sure that when you send the webelement.click(), your element is in clickable state? What happens? Nothing? Then again, if the actions click is reliably working, why not just go with it, I mean, if something works, why fix it?

Click on a first table row

There are two more ways to click on an element please try these out - it might work

  1. Using Action class
  2. JavaScript Executor

*Also Wait for Table to load before these code

** Action Class

    Actions action = new Actions(driver);
WebElement element = driver.findElement(By.xPath("//div[@role='row'][@row-index='0']/div"));
action.moveToElement(element).click().perform();

** JavaScript Executor

WebElement element = driver.findElement(By.xPath("//div[@role='row'][@row-index='0']/div"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);


Related Topics



Leave a reply



Submit