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.
How to click an element with Selenium webdriver javascript?
Thank you for your help. The problem was not in my code. The problem was with the https://www.facebook.com/ .
Because facebook, is changing the ID, and sometimes it was the login button sometimes a gender custom button. :/
Selenium: how to click on javascript button
Don't go through JavaScript. Try this:
String xPath = "//button[contains(.,'Login')]";
driver.findElement(By.xpath(xPath))).click();
Better yet, but not tested:
// xPath to find a button whose text() (ie title) contains the word Login
String xPath = "//button[contains(text(),'Login')]";
driver.findElement(By.xpath(xPath))).click();
Please also note that https://sqa.stackexchange.com/ has info on Selenium (etc.)
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 ?
I can´t click on an element with selenium, how can i click anyways?
I think you're using Selenium with JavaScript , I'm providing a suggestion, you can try this one if it works for you.
let input_provinces = await driver.findElement(By.id("select_provinces"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", input_provinces);
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 andzIndex
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 theclick
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.
Click Element in Selenium Javascript not working
Found the answer
Declared thisconst {Builder, By, Key, until} = require("selenium-webdriver");
and used
let query = driver.wait(until.elementLocated(By.id('email-popup-close-button')));
await query.click();
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
Related Topics
Kafka - Unable to Send a Message to a Remote Server Using Java
Spring JSON Request Getting 406 (Not Acceptable)
Convert Character to Ascii Numeric Value in Java
Generate All Combinations from Multiple Lists
How to Decompile a Whole Jar File
Spring Boot, Spring Data JPA with Multiple Datasources
How to Iterate an Arraylist Inside a Hashmap Using Jstl
Test If Element Is Present Using Selenium Webdriver
How to Update a Textview of an Activity from Another Class
Javafx Freeze on Desktop.Open(File), Desktop.Browse(Uri)
How to Click an Element in Selenium Webdriver Using JavaScript
Why Call Super() in a Constructor
How to Convert a Char Array Back to a String
How to Sort a List Alphabetically
Unsupportedoperationexception When Trying to Remove from the List Returned by Array.Aslist