How to click on Javascript button in Selenium with no ID (Java)? - javascript

I'm setting up a program in Java with Selenium.
At the start of the program, a Chrome extension I'm using with the program loads up with the Chrome instance.
Chrome then navigates to that page, selects all the boxes, and is supposed to click a button on the page that appears because of the extension.
So I am trying to click that button, but it's a Javascript button that comes on the page through the extension. There is no ID that I can use explicitly though.
When I inspect the element, all I see is this:
<a href="javascript:void(0);" class="selected button-task"
style="width: 140px; margin-left: 5px; height: 23px;">
<img src="websiteimage.png here" width="20px">Selected Task</a>
Unlike the other stuff I can click on, there is no type (checkboxes, button, etc) or a specific ID I can seek out. But it is important I click this button. What should I do?
I get this error when I use this:
Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector:
Unable to locate an element with the xpath expression //a[contains#class,'selected'] and contains(#class, 'repost-selected button-task') and contains(text(), 'Repost Selected') because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document':
The string '//a[contains#class,'selected'] and contains(#class, 'repost-selected button-task') and contains(text(), 'Repost Selected')' is not a valid XPath expression.
Thanks!

But it is important I click this button. What should I do?
You can click this button using following approaches :-
WebDriverWait wait = new WebDriverWait(driver,10);
using By.cssSelector() :-
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.selected.button-task"))).click();
using By.linkText() :-
wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Selected Task"))).click();
using By.partialLinkText() :-
wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("Selected Task"))).click();
using By.xpath() :-
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//a[normalize-space()='Selected Task']"))).click();

Try This:
driver.findElement(By.xpath("//a[contains#class,'selected'] and contains(#class, 'button-task') and contains(text(), 'Selected Task')")).click()

I figured out how to solve it:
WebElement extensionBox = driver.findElement(By.xpath(".//a[normalize-space()='Selected Task']"));
Actions actionsTwo = new Actions(driver);
JavascriptExecutor jseTwo = (JavascriptExecutor) driver;
actionsTwo.moveToElement(extensionBox).click();
jseTwo.executeScript("arguments[0].click()", extensionBox);
The other answers weren't working because they either wouldn't find the object on the page, or would give compile errors

Related

Robot Framework: Click button using execute javascript

This is the web inspection
<span jsslot="">
<button class="LkLjZd ScJHi IfEcue HPiPcc KXT7c" jsaction="click:yTqzwd" jsname="HxVe9c" autofocus="">Install</button>
</span>
I want to click on this element using the keyword Execute Javascript. I try like this
Execute JavaScript document.evaluate("//button[contains(text(),'Install')]",document.body,null,9,null).singleNodeValue.click()
After run test, it is PASS but no any action on web. It's still at the same. Could you please help?
I've already found the solution. According to there are several iframe, so should be select expected iframe before execute above command like this
Select Frame xpath=//*[#id="obj"]/div[5]/iframe
Execute JavaScript document.evaluate("//button[contains(text(),'Install')]",document.body,null,9,null).singleNodeValue.click()
Robot Framework: Click Element using Execute JavaScript
Already there is a answer for your question in the above link. Just copied and pasting one of the solution here.
${element_xpath}= Replace String ${element_xpath} \" \\\"
Execute JavaScript document.evaluate("${element_xpath}", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).click();
Also there are multiple solution in the link, try that.

How do I dump entire dom structure using selenium webdriver

I am new at selenium and python, and I am having problems finding the best way to identify the page elements I need for my automation.
I have a webpage with a lot of javascript on it. When I use firefox's inspect element for the username field in the login form, I see an input tag with an id, but when I ask selenium to find that id it says it can't be found.
I want to double-check that what I saw in firefox is actually what selenium is seeing, so I tried:
with open("login.html","w") s f:
f.write(driver.page_source)
I see no input elements at all in the resulting file.
Based on another stackoverflow question I tried:
DOM=driver.execute_script("return document.documentElement.outerHTML")
with open("login.html","w") as f:
f.write(DOM)
Still no input elements.
Is there a better way to see all the dom elements and/or find the correct xpath/ids to sue for my selenium script ?
Try get all body HTML by document.body.innerHTM
html = driver.execute_script("return document.body.innerHTML;")
with open("login.html","w") as f:
f.write(html)
#yong, your suggestion of adding a long sleep before the execute_script was the right answer. Now I can see the entire html source in the file I created.
In addition now my PageObject code works to fill in the login form and submit it. I do another sleep and then print the pageurl and title to make sure I have moved on to the next page.
Final code:
driver = webdriver..Firefox()
driver.set_page_load_time(60)
driver.get(URL)
time.sleep(60)
print("URL: "+driver.current_url)
print("Title: "driver.title)
page=LoginPage(driver)
page.username="username"
page.password="password"
page.signin_button.click()
time.sleep(60)
print("URL: "+driver.current_url)
print("Title: "+driver.title)
driver.quit()
Thank you everyone for the suggestions.

Click element with selenium with java

I am trying to click on the "connect" button of linkedin and I can not, I have already tried in every possible way.
Explicit wait:
WebDriverWait espere_estar_pronto_para_clicar = new WebDriverWait(driver, 50); espere_estar_pronto_para_clicar.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("Conectar")));
HTML Page Structure:
<button aria-label="Conecte-se a Eduardo G. K. Perez." class="search-result__actions--primary button-secondary-medium m5" data-ember-action="" data-ember-action-1876="1876">Conectar</button>
Click Attempts:
Attempt 1:
List<WebElement> conectar = driver.findElements(By.xpath("//button[text()='Conectar']"));
conectar.click();
Attempt 2:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(98,75, 32)");
Attempt 3:
driver.findElement(By.xpath("//*[#class='search-result__actions--primary.button-secondary-medium.m5']/button/text()")).click();
error:
Expected condition failed: waiting for element to be clickable:
By.partialLinkText: Conectar (tried for 50 second(s) with 500
MILLISECONDS interval)
Have you tried to take the XPath direct from a browser? (Chrome example below)
Right click on the element
Inspect Element
Right click on DOM
Select Copy
Click XPath
Paste in By.xpath(TEXT_COPIED)
If isn't that, I guess is the way you are trying to wait the button load.
The below code will do tested on my local, assuming you are going on
particular user profile page whom you want to connect once you signed-in and then clicking on Connect page
driver.findElement(By.xpath("//div[contains(#class,'pv-top-card-section__actions')]")).findElement(By.xpath("//span[contains(#class,'default-text') and contains(text(), 'Connect')]")).click();
Explanation :
1. driver.findElement(By.xpath("//div[contains(#class,'pv-top-card-section__actions')]")) this is parent div which has the Inmail and connect button within it, so I am locating the parent div keeping my driver to a limited area.
findElement(By.xpath("//span[contains(#class,'default-text') and contains(text(), 'Connect')]")).click(); fairly straightforward locating the element to be click on based on the class name and to be more accurate giving a context of text() which 'Connect' and clicking on the element.
Let me know if this does not works or in case you are facing any issues.
the automation is looking for an element that has not yet loaded, because the page loads the elements as the Scroll is triggered, so, the element searched was not yet on the page, because the Scroll had not yet been triggered.
JavascriptExecutor jsx = (JavascriptExecutor)driver;
//Go down 1000px
jsx.executeScript("window.scrollBy(0,1000)", "");
//up 1000px
jsx.executeScript("window.scrollBy(0,-1000)", "");

Selenium Webdriver with Python: Element is not clickable & Cannot read property 'click' of null

when running this command, I'm getting an error:
driver.find_element_by_link_text("Confirm").click()
selenium.common.exceptions.WebDriverException: Message: unknown error: Element ... is not clickable at point (67, 581). Other element would receive the click: `<div class="mfp-container mfp-ajax-holder mfp-s-loading">...</div>`
After searching answers on this issue, I've changed the above code to:
element = driver.find_element_by_link_text("Confirm").click()
driver.execute_script("arguments[0].click();", element)
For the first click it worked and then printed this error:
selenium.common.exceptions.WebDriverException: Message: unknown error: Cannot read property 'click' of null
The HTML code is:
Confirm
So this worked for me:
driver.find_element_by_link_text("Confirm").send_keys('\n')
Thanks to everybody :)
Try to search for the class:
driver.find_element_by_class("c-button js-close s-vgLeft0_5 c-button--blue").click()
If you look at the error message, you will see that another element is intercepting the click. I don't know for sure without looking at the page but generally it's something like a loader screen, popup, etc. that appears temporarily and then disappears. There is also the hint of one of the classes of the intercepting DIV, mfp-s-loading, that further makes me think it's some sort of loading popup. The problem here is that the script proceeds and tries to click the link faster than the popup loads and unloads. What I typically do in a situation like this is to wait for the popup to be invisible and then click the link.
The HTML of the popup is in the error message,
<div class="mfp-container mfp-ajax-holder mfp-s-loading">...</div>
So you can locate the element using a CSS selector like, div.mfp-s-loading, to wait for it to be invisible and then try your click.
Sometimes using Xpath is easier
Try:
driver.find_element_by_xpath(Xpath).click()
where Xpath should point to the object which you are planning to click

Unable to click the Link in selenium webdriver

I am trying to Click on Link. But it is showing Element Not found Message. Here is my HTML Code:
<a id="expTo" class="formblue_link padRight10
exportLinkActive" style="display: block; margin-left: -50px; margin-bottom: -20px;" href="javascript:;"> Export To</a>
My code is:
`driver.findElement(By.linkText("Export To")).click();`
It's recomanded to not try to find element by button or item text. This can be easy changed while page is still in develop so I would suggest to use click by id instead of by text
driver.findElement(By.id("expTo")).click();
There is also alternative to click by css for example:
driver.findElement(By.cssSelector(".css-class-name"));
All others selectors can be found here
You should try using WebDriverWait to wait until element visible and clickable as below :-
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.id("expTo"))).click();
Note :- Before going to find this element, make sure it is not inside any frame/iframe. If it exists inside any frame/iframe, you need to switch that frame/iframe before finding it as :-
driver.switchTo().frame("frame/iframe name or id");

Categories