Selenium how to click/ access an a tag with a href that has a javascript function - selenium

I have searched but havent found something similar to what Im trying to do. I'm using java by the way, I'm trying to click/access an a tag with selenium. The issue is that I'm not sure how to go about it. There seems to be a function/event that I need to set off but not quite sure how to. I tried a few ways as get text and clicking but I knew that wasn't going to work. Also I seen there are ways of using JavascriptExecutor but not sure how to use it for my case. I will post the tag below and alsothe function signature, that might help. If theres a similar question please post the link.
<a name="DERIVED_SSS_SCL_SSS_ENRL_CART$276$" id="DERIVED_SSS_SCL_SSS_ENRL_CART$276$" ptlinktgt="pt_peoplecode" tabindex="203" onclick="javascript:cancelBubble(event);" href="javascript:submitAction_win0(document.win0,'DERIVED_SSS_SCL_SSS_ENRL_CART$276$');" class="SSSHYPERLINKBOLDSMALL">Enrollment Shopping Cart</a>
the signature
function submitAction_win0(form, id, event)

You don't need any JS. Just use this xpath:
"//a[contains(#onclick,'javascript:cancelBubble(event);')]"
Be sure the element is clickable, see
import org.openqa.selenium.support.ui.ExpectedConditions;
for the case of more matches:
List<WebElement> elements = driver.findElements(By.xpath("//a[contains(#onclick,'javascript:cancelBubble(event);')]"));
int elementIndex = 0; // 0 to get first of the 33 mathes, 32 to get the last one
WebElement element = elements.get(elementIndex);
element.click();

EDIT:
You should use WebDriverWait to avoid NoSuchElementException this way the driver will wait until the element is clickable... it will wait up to 10 seconds you can tell it to wait more if needed...
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("Student Center")));
element.click();
Using click():
WebElement element = driver.findElement(By.cssSelector("a[class='SSSHYPERLINKBOLDSMALL']"));
element.click();
Using JavascriptExecutor (Not recommended):
WebElement element = driver.findElement(By.cssSelector("a[class='SSSHYPERLINKBOLDSMALL']"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
You can use other locators too... like linkText:
WebElement element = driver.findElement(By.linkText("Enrollment Shopping Cart"));
Or partialLinkText:
WebElement element = driver.findElement(By.partialLinkText("Shopping Cart"));

Related

Cannot read property 'defaultView' of undefined

<a href="/lightning/n/******__Country" title="Country" tabindex="0" draggable="false" aria-describedby="operationId-17" class="slds-context-bar__label-action dndItem">
<span class="slds-truncate">Country</span></a>
I got the xpath as
WebElement tabName = driver.findElement(By.xpath("//a[contains(#href,'Country')]"));
I need to click the Country link
I have tried the following options but none work
1) driver.findElement(By.xpath("//a[contains(#href,'Country') and #title='Country']")).click();
2) Actions actions = new Actions((WebDriver) driver.getWebDriver());
actions.moveToElement(tabName).click().perform();
3) ((JavascriptExecutor) driver).executeScript("arguments[0].click();", tabName);
waitForSeconds(5);
I am getting invocation of target exception
org.openqa.selenium.WebDriverException: javascript error: Cannot read
property 'defaultView' of undefined
Can any one please tell me how to click the href link?
Try click on its parent/ancestor instead. For example, if you had
//a[text()='link of your text']
and you get the javascript error, try:
//a[text()='link of your text']/parent::*
Try the following code - it works against Salesforce Lightning UI screens:
WebElement element = driver.findElement(By.xpath("your xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
Sharing it after testing it and found to be working.
To click on the following link use WebDriverWait and elementToBeClickable and then click on the link using the following xpath.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[#title='Country']/span[#class='slds-truncate'][contains(.,'Country')]"))).click();
For those trying out in python, here is how you do it:
>>> button_link = driver.find_element_by_xpath('''//*[#id="tab-23"]/slot''')
>>> driver.execute_script("arguments[0].click();", button_link )
Try JavaScript. It worked for me
WebElement element = driver.findElement(By.xpath("strPath"));
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);

Unable to use elements within iframe after switching

I am using switching to an iframe using the below statements but on the final wait I get web element not found. Does anyone have any suggestions? I have trolled through google for about a day trying different techniques. None have worked so far
WebDriver driver = DriverFactory.getWebDriver()
WebDriverWait wait = new WebDriverWait(driver, 15)
driver.switchTo().defaultContent()
WebElement iframe = driver.findElement(By.cssSelector(".b-iframe__iframe"))
driver.switchTo().frame(iframe)
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(
'fieldset.radio-switch-group')))
Screen shot of HTML below image
As per the HTML you have shared to locate the desired WebElement you have to:
Induce WebDriverWait for the desired frame to be available and switch to it.
Induce WebDriverWait for the desired element to be visible and you can use either of the following solutions:
Using cssSelector:
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe.b-iframe__iframe[src*='securetest']")));
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("fieldset.radio-switch-group#balance-type")));
Using xpath:
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[#class='b-iframe__iframe' and contains(#src,'securetest')]")));
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//fieldset[#class='radio-switch-group' and #id='balance-type']")));
Here you can find a relevant discussion on Ways to deal with #document under iframe

Unable to find element with xpath for Add -ons text (Correct xpath)

driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get("http://www.spicejet.com");
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//a[contains(text(),'Add-Ons')]")))
.build().perform();
Thread.sleep(3000);
driver.findElement(By.linkText("Hot Meals ")).click();
driver.close();
Unable to locate element with xpath //a[contains(text(),'Add-Ons')
Its it regarding frames?
your xpath can find the correct element when I verify it by manual. I suspect the page not load completely, please add some sleep after dirver.get() for debug purpose.
driver.get("http://www.spicejet.com");
Thread.sleep(10*1000) // sleep 10 seconds to wait page open completely.
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//a[contains(text(),'Add-Ons')]")))
.build().perform();
Sometimes exact element can't be found using By.linkText()
You just use cssSelector like below:
driver.findElement(By.cssSelector("#header-addons > ul > li:nth-child(5) > a")).click();
Thread.sleep(3000);
instead of the line driver.findElement(By.linkText("Hot Meals ")).click();
You can also use xpath instead like below:
driver.findElement(By.xpath("//*[#id=\"header-addons\"]/ul/li[5]/a")).click();
Thread.sleep(3000);

Selenium click not work

Help me please.
Selenium does not click on element and element is clickable(selenium does not generate exception).
I try use Id, css, xpath locators, nothing did not help me.
What should i do to decide my problem?
Java code example.
WebElement sector = webDriver.findElement(By.id("sector-1"));
sector.click();
After click system must open this page
Seems that you try to interact with object inside a <svg> element. If so, you cannot manage it's child elements simply using click() method.
Try this instead:
WebElement svgObject = driver.findElement(By.xpath("//polygon[#id='sector-1:canvas']"));
Actions builder = new Actions(driver);
builder.click(svgObject).build().perform();
Use below XPath :
WebElement sector = webDriver.findElement(By.xpath("//g[#id='sector-1']/polygon"));
sector.click();
OR
WebElement sector = webDriver.findElement(By.xpath("//polygon[#id='sector-1:canvas']"));
sector.click();
I decide my problem.
WebDriverWait wait = new WebDriverWait(webDriver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"sector-2:canvas\"]")));
WebElement svgObject = webDriver.findElement(By.xpath("//*[#id=\"sector-2:canvas\"]"));
Actions builder = new Actions(webDriver);
builder.click(svgObject).build().perform();

Scroll Element into View with Selenium

Is there any way in either Selenium 1.x or 2.x to scroll the browser window so that a particular element identified by an XPath is in view of the browser? There is a focus method in Selenium, but it does not seem to physically scroll the view in FireFox. Does anyone have any suggestions on how to do this?
The reason I need this is I'm testing the click of an element on the page. Unfortunately the event doesn't seem to work unless the element is visible. I don't have control of the code that fires when the element is clicked, so I can't debug or make modifications to it, so, easiest solution is to scroll the item into view.
Have tried many things with respect to scroll, but the below code has provided better results.
This will scroll until the element is in view:
WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
//do anything you want with the element
You can use the org.openqa.selenium.interactions.Actions class to move to an element.
Java:
WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();
Python:
from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).move_to_element(driver.sl.find_element_by_id('my-id')).perform()
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:window.scrollBy(250,350)");
You may want to try this.
If you want to scroll on the Firefox window using the Selenium webdriver, one of the ways is to use JavaScript in the Java code. The JavaScript code to scroll down (to bottom of the web page) is as follows:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight));");
Targeting any element and sending down keys (or up/left/right) seems to work also. I know this is a bit of a hack, but I'm not really into the idea of using JavaScript to solve the scrolling problem either.
For example:
WebElement.sendKeys(Keys.DOWN);
In Selenium we need to take the help of a JavaScript executor to scroll to an element or scroll the page:
je.executeScript("arguments[0].scrollIntoView(true);", element);
In the above statement element is the exact element where we need to scroll. I tried the above code, and it worked for me.
I have a complete post and video on this:
http://learn-automation.com/how-to-scroll-into-view-in-selenium-webdriver/
webElement = driver.findElement(By.xpath("bla-bla-bla"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", webElement);
For more examples, go here. All in Russian, but Java code is cross-cultural :)
I found that the bounding rect of my element was not correct, leading to the browser scrolling well off the screen. However, the following code works rather well for me:
private void scrollToElement(WebElement webElement) throws Exception {
((JavascriptExecutor)webDriver).executeScript("arguments[0].scrollIntoViewIfNeeded()", webElement);
Thread.sleep(500);
}
You can use this code snippet to scroll:
C#
var element = Driver.FindElement(By.Id("element-id"));
Actions actions = new Actions(Driver);
actions.MoveToElement(element).Perform();
There you have it
This worked for me:
IWebElement element = driver.FindElements(getApplicationObject(currentObjectName, currentObjectType, currentObjectUniqueId))[0];
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
Use the driver to send keys like the pagedown or downarrow key to bring the element into view. I know it's too simple a solution and might not be applicable in all cases.
From my experience, Selenium Webdriver doesn't auto scroll to an element on click when there are more than one scrollable section on the page (which is quite common).
I am using Ruby, and for my AUT, I had to monkey patch the click method as follows;
class Element
#
# Alias the original click method to use later on
#
alias_method :base_click, :click
# Override the base click method to scroll into view if the element is not visible
# and then retry click
#
def click
begin
base_click
rescue Selenium::WebDriver::Error::ElementNotVisibleError
location_once_scrolled_into_view
base_click
end
end
The 'location_once_scrolled_into_view' method is an existing method on WebElement class.
I apreciate you may not be using Ruby but it should give you some ideas.
The Ruby script for scrolling an element into view is as below.
$driver.execute_script("arguments[0].scrollIntoView(true);", element)
sleep(3)
element.click
Selenium 2 tries to scroll to the element and then click on it. This is because Selenium 2 will not interact with an element unless it thinks that it is visible.
Scrolling to the element happens implicitly so you just need to find the item and then work with it.
Sometimes I also faced the problem of scrolling with Selenium. So I used javaScriptExecuter to achieve this.
For scrolling down:
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollBy(0, 250)", "");
Or, also
js.executeScript("scroll(0, 250);");
For scrolling up:
js.executeScript("window.scrollBy(0,-250)", "");
Or,
js.executeScript("scroll(0, -250);");
This is a repeated solution with JavaScript, but with an added waiting for element.
Otherwise ElementNotVisibleException may appear if some action on the element is being done.
this.executeJavaScriptFunction("arguments[0].scrollIntoView(true);", elementToBeViewable);
WebDriverWait wait = new WebDriverWait(getDriver(), 5);
wait.until(ExpectedConditions.visibilityOf(elementToBeViewable));
I have used this way for scrolling the element and click:
List<WebElement> image = state.getDriver().findElements(By.xpath("//*[contains(#src,'image/plus_btn.jpg')]"));
for (WebElement clickimg : image)
{
((JavascriptExecutor) state.getDriver()).executeScript("arguments[0].scrollIntoView(false);", clickimg);
clickimg.click();
}
def scrollToElement(element: WebElement) = {
val location = element.getLocation
driver.asInstanceOf[JavascriptExecutor].executeScript(s"window.scrollTo(${location.getX},${location.getY});")
}
Something that worked for me was to use the Browser.MoveMouseToElement method on an element at the bottom of the browser window. Miraculously it worked in Internet Explorer, Firefox, and Chrome.
I chose this over the JavaScript injection technique just because it felt less hacky.
You may want to visit page Scroll Web elements and Web page- Selenium WebDriver using Javascript:
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FirefoxDriver ff = new FirefoxDriver();
ff.get("http://toolsqa.com");
Thread.sleep(5000);
ff.executeScript("document.getElementById('text-8').scrollIntoView(true);");
}
If you think other answers were too hacky, this one is too, but there is no JavaScript injection involved.
When the button is off the screen, it breaks and scrolls to it, so retry it... ¯\_(ツ)_/¯
try
{
element.Click();
}
catch {
element.Click();
}
In most of the situation for scrolling this code will work.
WebElement element = driver.findElement(By.xpath("xpath_Of_Element"));
js.executeScript("arguments[0].click();",element);
JAVA
Try scroll to element utilize x y position, and use JavascriptExecutor with this is argument: "window.scrollBy(x, y)".
Following import:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
First you need get x y location the element.
//initialize element
WebElement element = driver.findElement(By.id("..."));
//get position
int x = element.getLocation().getX();
int y = element.getLocation().getY();
//scroll to x y
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(" +x +", " +y +")");
I am not sure if the question is still relevant but after referring to scrollIntoView documentation from https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView.
The easiest solution would be
executor.executeScript("arguments[0].scrollIntoView({block: \"center\",inline: \"center\",behavior: \"smooth\"});",element);
This scrolls the element into center of the page.
Javascript
The solustion is simple:
const element = await driver.findElement(...)
await driver.executeScript("arguments[0].scrollIntoView(true);", element)
await driver.sleep(500);
The default behavior of Selenium us to scroll so the element is barely in view at the top of the viewport. Also, not all browsers have the exact same behavior. This is very dis-satisfying. If you record videos of your browser tests, like I do, what you want is for the element to scroll into view and be vertically centered.
Here is my solution for Java:
public List<String> getBoundedRectangleOfElement(WebElement we)
{
JavascriptExecutor je = (JavascriptExecutor) driver;
List<String> bounds = (ArrayList<String>) je.executeScript(
"var rect = arguments[0].getBoundingClientRect();" +
"return [ '' + parseInt(rect.left), '' + parseInt(rect.top), '' + parseInt(rect.width), '' + parseInt(rect.height) ]", we);
System.out.println("top: " + bounds.get(1));
return bounds;
}
And then, to scroll, you call it like this:
public void scrollToElementAndCenterVertically(WebElement we)
{
List<String> bounds = getBoundedRectangleOfElement(we);
Long totalInnerPageHeight = getViewPortHeight(driver);
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("window.scrollTo(0, " + (Integer.parseInt(bounds.get(1)) - (totalInnerPageHeight/2)) + ");");
je.executeScript("arguments[0].style.outline = \"thick solid #0000FF\";", we);
}
I've been doing testing with ADF components and you have to have a separate command for scrolling if lazy loading is used. If the object is not loaded and you attempt to find it using Selenium, Selenium will throw an element-not-found exception.
If nothing works, try this before clicking:
public void mouseHoverJScript(WebElement HoverElement) {
String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
((JavascriptExecutor) driver).executeScript(mouseOverScript, HoverElement);
}
In Java we can scroll by using JavaScript, like in the following code:
driver.getEval("var elm = window.document.getElementById('scrollDiv'); if (elm.scrollHeight > elm.clientHeight){elm.scrollTop = elm.scrollHeight;}");
You can assign a desired value to the "elm.scrollTop" variable.
A solution is:
public void javascriptclick(String element)
{
WebElement webElement = driver.findElement(By.xpath(element));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", webElement);
System.out.println("javascriptclick" + " " + element);
}