Click link under navigation bar in Selenium Webdriver - selenium-webdriver

I am trying to click the link under the navigation bar. I tried driver.findelement in this code snippet. It selects the link but the click event is not taking place.
WebElement menu=driver.findElement(By.xpath(".//*[#id='bs-example-navbar-collapse-1']"));
//WebElement menu = driver.findElement(By.XPATH("Coplete_navigationbar_xpath")); List<WebElement>
List<WebElement> allLinks = menu.findElements(By.tagName("a"));
String MenuOptn="";
for (WebElement w : allLinks)
{
MenuOptn=w.getText();
if(MenuOptn.equalsIgnoreCase("TRACKING"))
{
// System.out.println("tracking");
w.click();
System.out.println("tracking");
break;
}
System.out.print(w.getText());
}

Try click using javascript
WebElement element = webDriver.findElement(locator);
JavascriptExecutor executor = (JavascriptExecutor) webDriver;
executor.executeScript("arguments[0].click();", element);

Try below options:
driver.FindElement(By.Xpath("//a[contains(., '<link_text>')]")).click();
or
new Actions(driver).moveToElement(driver.FindElement(By.Xpath("//a[contains(., '<link_text>')]")),10,10).doubleClick().perform();
I hope it will be helpful

Related

How to handle the modules which are under the same menu by using single xpath expression for all the modules

this is the example from our application
I am trying this code but not working
WebElement ele=driver.findElement(By.xpath("//a[#title='Menu for Distribution']"));
Actions act=new Actions(driver);
act.moveToElement(ele).perform();
Thread.sleep(3000);
for (int i=3; i<=10; i++)
{
System.out.println(i);
ele1=driver.findElement(By.xpath("//a[#target='frame_main'])[i]"));
ele1.click();
}
Please use the following method to click submenu option,
by calling clickSubMenu("New Consignee");
public void clickSubMenu(String optionName){
By mainMenu = By.xpath("//a[#title='Menu for Distribution']");
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(mainMenu));
action.build().perform();
By subMenu = By.xpath("//a[text()='"+optionName+"']");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(subMenu));
driver.findElement(subMenu).click();
}
Steps :
Hover over to the main menu
wait for the visiblity
Click the submenu

Why does Selenium sometimes skip checkboxes?

I'm having troubles regarding webdriver not being able to click checkboxes sometime and just skipping them, both in Firefox and Chrome.
I've tried different solutions such as
click();
action.moveToElement(checkbox).clickAndHold(checkbox).release().perform();
jse.javascriptExecutor(argument[0].click(),checkbox).
Here I provide the Javascript code I have for the click event
...
var selectCorrectOption = function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
$(this).find('> input').prop('checked', false);
} else {
$(this).addClass('selected');
$(this).find('> input').prop('checked', true);
}
};
$('.option > .input-container').on('click', selectCorrectOption);
...
the HTML code where it is attached the javascript click event
<div class="input-container selected" data-choice-id="2">
<input type="radio">
</div>
the Java code data uses a data-attribute to access the element is question. Notice also that once the div is clicked, a 'selected' class appears(which is the current state) on the code below.
WebDriverWait wait = new WebDriverWait(driver, 20);
JavascriptExecutor jse = (JavascriptExecutor)driver;
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-choice-id='"+ wrongOptionVal +"']")));
radio=wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("[data-choice-id='"+ wrongOptionVal +"']")));
jse.executeScript("arguments[0].scrollIntoView()", radio);
jse.executeScript("arguments[0].click()", radio);
I expected it to be consistent ,most of the times work, but there are always that one or two times it fails.
I do not know why this happens, I do however know how this can be addressed. You can implement a FluentWait with polling mechanism, which will do three things:
locate the element,
select the radio box,
return getAttribute("class").contains("selected") value.
If getAttribute("class").contains("selected") will result in false the process should repeat.
FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
.pollingEvery(Duration.ofMillis(300))
.withTimeout(Duration.ofSeconds(10));
fluentWait.until(new Function<WebDriver, Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
WebElement element = driver.findElement(By.cssSelector(radioCssSelector));
element.click();
return element.getAttribute("class").contains("selected");
}
});

Selenium Webdriver Java

I have a query on mouseover action in Selenium Webdriver Java.
Consider i have a background image with id "Lfade" with opacity 0.5. If i hover the mouse then a button would be shown.
I want to click on the button to take me to another screen. How do i do this ???
I have tried this, but it does not work
Actions builder = new Actions(driver);
WebElement tagElement = driver.findElement(By.id("Lfade"));
builder.moveToElement(tagElement).build().perform();
Html
div id="homeslant"
div id="wrapper"
div id="lFade" class="learn" style="opacity: 0.5; visibility: visible;"
Button
div class="descbtn"
a class="btn dwmbutton" href="/learn/index.html">KNOW MORE</a>
Not sure about what you are trying to do but I notice an error here:
builder.moveToElement(tagElement).build().perform();
Actually, the .perform() includes a .build().
May be you were referring to .click() so
builder.moveToElement(tagElement).click().perform()
As a pattern for your objective I would:
find the first image
move to the image
wait
find the button
click the button
I used Robot class for mouse hover. Please try the below code.
Robot robot = new Robot();
Point MyPoint = tagElement.getLocation();
robot.mouseMove(MyPoint.getX(), MyPoint.getY());
After that use the normal selenium click to click on the button.
You need to move to the button and perform a click.
Move to the image
wait
Move to the button and click
Actions act = new Actions(driver);
WebElement tagElement = driver.findElement(By.id("Lfade"));
act.moveToElement(tagElement).click().build().perform();
WebElement _button= driver.findElement(By...);
act.moveToElement(_button).click().build().perform();
Try this
#FindBy(xpath="//*[#id='chromemenu']/span/a") WebElement menuHoverLink;
#FindBy(xpath="//*[#id='dropmenu1']/a[1]") WebElement subLink;
Actions maction = new Actions(driver);
maction.moveToElement(menuHoverLink).build().perform();
Thread.sleep(2000);
subLink.click();
Use this code it will work :
Actions builder = new Actions(driver);
WebElement tagElement = driver.findElement(By.id("Lfade"));
WebElement buttonElement = driver.findElement(By.classname("btn"));
builder.moveToElement(tagElement).moveToElement(buttonElement).click().perform();
Try this
public void HoverAndClickObject(WebDriver driver, String property1, String property2, String path) throws SAXException, IOException, ParserConfigurationException
{
//get object properties from the xml file repository
Actions action = new Actions(driver);
String[] element1 = xmlParser(path, property1);
String[] element2 = xmlParser(path, property2);
switch (element1[0].toUpperCase())
{
case "XPATH":
driver.findElement(By.xpath(element1[1])).click();
action.moveToElement(driver.findElement(By.xpath(element2[1]))).click().build().perform();
break;
case "ID":
driver.findElement(By.id(element1[1])).click();
break;
case "NAME":
driver.findElement(By.name(element1[1])).click();
break;
case "LINKTEXT":
driver.findElement(By.linkText(element1[1])).click();
break;
case "CSSSELECTOR":
driver.findElement(By.cssSelector(element1[1])).click();
break;
}
}

Press TAB and then ENTER key in Selenium WebDriver

Press TAB and then ENTER key in Selenium WebDriver
GenericKeywords.typein(class.variable, PageLength);
pagelength is nothing but string.
After this code, I have to give Tab key. I don't know how to give Tab key in Selenium WebDriver?
Using Java:
WebElement webElement = driver.findElement(By.xpath(""));//You can use xpath, ID or name whatever you like
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);
In javascript (node.js) this works for me:
describe('UI', function() {
describe('gets results from Bing', function() {
this.timeout(10000);
it('makes a search', function(done) {
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
driver.get('http://bing.com');
var input = driver.findElement(webdriver.By.name('q'));
input.sendKeys('something');
input.sendKeys(webdriver.Key.ENTER);
driver.wait(function() {
driver.findElement(webdriver.By.className('sb_count')).
getText().
then(function(result) {
console.log('result: ', result);
done();
});
}, 8000);
});
});
});
For tab use webdriver.Key.TAB
Using Java:
private WebDriver driver = new FirefoxDriver();
WebElement element = driver.findElement(By.id("<ElementID>"));//Enter ID for the element. You can use Name, xpath, cssSelector whatever you like
element.sendKeys(Keys.TAB);
element.sendKeys(Keys.ENTER);
Using C#:
private IWebDriver driver = new FirefoxDriver();
IWebElement element = driver.FindElement(By.Name("q"));
element.SendKeys(Keys.Tab);
element.SendKeys(Keys.Enter);
In python this work for me
self.set_your_value = "your value"
def your_method_name(self):
self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`
Be sure to include the Key in the imports...
const {Builder, By, logging, until, Key} = require('selenium-webdriver');
searchInput.sendKeys(Key.ENTER) worked great for me
Sometimes Tab will not move forward, you can use with combination of Tab and Enter keys as below
Using C# :
Driver.SwitchTo().Window(Driver.WindowHandles[1]);
IWebElement element = Driver.FindElement(By.TagName("body"));
element.SendKeys(Keys.Tab + Keys.Enter);
Driver.SwitchTo().Window(Driver.WindowHandles[0]);
WebElement webElement = driver.findElement(By.xpath(""));
//Enter the xpath or ID.
webElement.sendKeys("");
//Input the string to pass.
webElement.sendKeys(Keys.TAB);
//This will enter the string which you want to pass and will press "Tab" button .

Hover over an item in the dropdown list in selenium webdriver

How to hover over an item in the dropdown list in selenium webdriver? I knew about clicking, however I need to moverOver on each and every item and check the url is a secured one.
Thanks
You can hover you mouse on dropdown item but you can verify its url!
You can verify it by look at htlm code. For exmple:
<ul id="dropdown">
<li id="item001" class="">
Link 1
</li>
<li id="item002" class="">
Link 2
</li>
</ul>
In the html code above, I have a dropdown list with 2 items List 1 and List 2.
If you want to verify what link is in each item, you should get link from item (attribute href) and compare it to expected result.
Or even if you want verify title just get title attribute.
Hope useful.
When using Java, for example:
Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.xpath("xpath")));
Check this example how we could implement this.
public class HoverableDropdownTest {
private WebDriver driver;
private Actions action;
Consumer < By > hover = (By by) - > {
action.moveToElement(driver.findElement(by))
.perform();
};
#Test
public void hoverTest() {
driver.get("https://www.bootply.com/render/6FC76YQ4Nh");
hover.accept(By.linkText("Dropdown"));
hover.accept(By.linkText("Dropdown Link 5"));
hover.accept(By.linkText("Dropdown Submenu Link 5.4"));
hover.accept(By.linkText("Dropdown Submenu Link 5.4.1"));
}
#BeforeTest
public void setupDriver() {
driver = new FirefoxDriver();
action = new Actions(driver);
}
#AfterTest
public void teardownDriver() {
driver.quit();
}
}
For detailed answer, check here - http://www.testautomationguru.com/selenium-webdriver-automating-hoverable-multilevel-dropdowns/

Resources