Can we use click() functionality along with sendKeys()? - selenium

Can we use Click() functionality along with sendKeys()??
I just read a drop-down value using xpath and now i need to click on the particular value i have read. Actually its possible to use in two steps. But is there any option to read and click in a single code??
Thanks,
SK

Kindly try with this. I have used Enter key as a substitute for clicking.
driver.findElement(By.xpath("xpath")).sendKeys("Talk-Talk",K‌​eys.ENTER);
Hope this helps. Thanks.

If your requirement is to select some specific option in dropdown then use select class.
Go though this article for more info
But if you want to click on some element and then send some text, then you can user Action class.
WebElement wb = driver.findElement(By.xpath("your xpath"));
Actions action = new Actions(driver);
action.moveToElement(wb).click().moveToElement(wb,200, 0).sendkeys("text").build().perform();//you need to specify where you need to send text 200,0 is just as an example

Actions action = new Actions(driver);
WebElement MobileNumber = driver.findElement(By.xpath("yourxpath"));
action.moveToElement(MobileNumber).click().sendKeys("your text").build().perform();

Following the Java Docs, click() method returns void as follows:
void click()
Similarly, sendKeys() method also returns void as follows :
void sendKeys(java.lang.CharSequence... keysToSend)
So as per best programming practice we must not try to club-up click() method with sendKeys() method or vice versa. It would be ideal to achieve the intended task in two separate steps.

Related

Making dynamic code in Cucumber with the Page Object Model

Is there a way perform actions dynamically using Cucumber?
Example:
Feature File:
Scenario: Click all the boxes
Given On the checkbox page
When Click checkboxA
And Click checkboxB
Step Definition:
#When("Click checkboxA")
public void clickCheckBoxA()
{
pageObject.checkBoxA.click();
}
#And("Click checkboxB")
public void clickCheckBoxB()
{
pageObject.checkBoxB.click();
}
In this scenario, there are two very similar step definitions. The reason why there are two different definitions is because each WebElement is defined in the pageObject Class. Is there a way to dynamically pass which checkbox we want to click, rather than having two separate methods performing the same action?
The only way I can think to do this is by passing a selector as a parameter in the feature step and instantiating the webElement within the step definition method. But that seems like bad practice to me.
Click is your step. It should not be unique for each item you may want to click. You should match what you want to click with a regular expression. The following combines your two steps into one.
#When("^Click (.*)$")
public void clickElement(String elementToClick) {
switch (elementToClick) {
case "checkBoxA":
pageObject.checkBoxA.click();
case "checkBoxB":
pageObject.checkBoxB.click();
}
}
I'd suggest using a smarter regex match (this one is lazy and sloppy) and you could also create a new variable for the element to be clicked, assign its value to your existing element in each case and have a single call to click() after the switch statement.
Regarding your question of doing this "dynamically," you cannot do so in Java (I think you were thinking of having a single line in the example I gave above of pageObject.elementToClick.click();?) because it's a compiled programming language; your code can't be altered at runtime.
I would prefer to use #mike's solution, but in some cases I tend to create a locator as string in POM so that it reduces lines of code in the step definition.
Feature File:
Scenario: Click all the boxes
Given On the checkbox page
When Click checkbox A
And Click checkbox B
POM:
private String checkBox = "//input[text()='checkBox%s']";
Step Definition:
#When("Click checkbox (.*)")
public void handleCheckBox(String checkBoxName) {
driver.findElement(By.xpath(String.format(checkBox, checkBoxName))).click();
}

Selenium automation with xpath for all browsers

I am new to selenium automation and I am trying to figure out how to handle the code for an element that shows different xpath for different browsers.
//xpath for IE
private readonly By ByPermIE = By.XPath("//*[#id='group-permissions']/div[1]/div[2]/span[2]");
//xpath for chrome
private readonly By ByPermChrome = By.XPath("//*[#id='group-permissions']/div[1]/div[1]/span[2]");
If I am performing some action on this element on different browsers how do I use these elements in the test case. I am planning to extend this to three more browsers. So, should I use if else conditions everywhere? Is there any alternate of best practice for such cases?
You can use below xpath for you case.
private readonly By ByPermChrome = By.XPath("//*[#id='group-permissions']/div[1]//span[text() = 'text that span contains']");
You can write xpath as relative as possible.It is not advisable to write absolute xpaths.
For your above case use below xpath which works in both the browsers.
By.XPath("//*[#id='group-permissions']//span[2]");
or
By.XPath("//*[#id='group-permissions']//span[text()='someThing']");
Refer this for more info regarding xpath.
if u post ur html code, than it will be easy. But as there is no html given, i can suggest u a way like below:
//u can use if condition here
if(driver.findElements(By.XPath("//*[#id='group-permissions']/div[1]/div[2]/span[2]")).size()==1){
//perform operation here
}
else
//perform operation here
This is an alternative way as there is no html code.
If u give the html code, i think we can suggest u more be
One suggestion I can give here is you can use OR conditions in xpaths. Say OR OR .
Xpath OR returns successful as soon it hits the first correct one.

Page Factory #FindBy

I am currently learning page object model (POM) and I am trying to access a specific web element using #FindBy but I am not sure how to correctly write the syntax for my element into #FindBy?
What I have is:
driver.findElement(By.cssSelector("a[dta-qid='inventory']");
So my question is how do I place a[da-qid='inventory'] correctly into #FindBy?
By, a[da-qid='inventory'], what I mean is that it selects every <a> element whose da-qid value begins with 'inventory'.
Why do not you read through this? Use of #FindsBy is easier if you do that with How Enum. You have multiple options in that case. With cssSelector it should look like this
#FindBy(how = How.css, using = "a[dta-qid='inventory']")
WebElement foobar;
If you assume that multiple elements will be found using this selector, try the following:
#FindBy(css="a[da-qid='inventory']")
List<WebElement> elements;
Just don't forget to choose correctly between da-qid='inventory' and dta-qid='inventory'
You could use the XPath selector:
driver.findElement(By.xpath("//a[contains(#da-qid,'inventory')]");
or
#FindBy(xpath = "//a[contains(#da-qid,'inventory')]")
WebElement inventoryLink;
respectively
#FindAll(xpath = "//a[contains(#da-qid,'inventory')]")
List<WebElement> inventoryLinks;
Theoretically the XPath "//a[startsWith(#da-qid,'inventory')]" exists as well, but it didn't work in all WebDrivers for me.

How to select radiobutton through #FindBy annotation in selenium webdriver

While designing page object class we use #FindBy(name="value") i.e FindBy with name.
SO below code to find an webpage's textbox like username field.
#FindBy(name="username")
WebElement txtboxUname;
........//Inside testfunction we call this txtboxUname like below
txtboxuname.sendKeys("purnendu");
So for radio button page object how we define it through #FindBy???
Following code is not working
#FindBy(name="radio")
List<WebElement> radioBtnSelectTrip;
.......call inside function
radioBtnSelectTrip.get(0).click();
The above #FindBy technique is not working for radio button.can you please help how to define radiobutton through #FindBy and use it through Pagefactory
There are several techniques for UI mapping. While using #FindBy to map UI elements it is possible to map the element with xpath. However, you want to make sure the xpath is correct and only returns the target radio. See an example of how to find an element with xpath here
Explore more about the Annotation Type FindBy here
And,
#FindBy(name="radio")
List<WebElement> radioBtnSelectTrip;
will not return you ONE radio rather a list. To perform an action on a specific radio you need to add additional filter. such asif condition to match a unique criteria on the target radio button.
Edit Added code to explore how FindBy can be implementation in finding a specific radio
#FindBy(how = How.CSS, using = "[type='radio'][value='roundtrip']")
public WebElement roundTrip;
#FindBy(how = How.CSS, using = "[type='radio'][value='oneway']")
public WebElement oneWay;
You have a typo. If you want to return a radio button, you probably want to select by it's type: #FindBy(xpath="//input[#type='radio']").

How to verify a target="_blank" link using selenium?

Some links on our page open in a new window using target="_blank". How can I make selenium look at the right window so I can verify that the page is linking to the right page?
Here's what I've been trying:
open /page/
click link=Find us on Facebook!
pause 2000
selectWindow title=window title
verifyTextPresent some text
You don't need to pass a parameter to selectWindow. The browser will automatically give your new window focus, you just need to tell selenium that it's changed. Also make sure you give your new window enough time to actually load before verifying anything:
open /page
click link=Find us on Facebook!
pause 1000
selectWindow
verifyTextPresent some text
$this->click('css=.sf_admin_action_page:first a');
$this->waitForPopUp('_blank');
$this->selectWindow('_blank');
$this->waitForElementPresent('css=.t-info:contains(xxx2)');
// ps. selenium2
you should use selectPopUp to focus the new window. see its document:
selectPopUp:
Arguments:
windowID - an identifier for the popup window, which can take on a number of different meanings
Simplifies the process of selecting a popup window (and does not offer functionality beyond what selectWindow() already provides).
If windowID is either not specified, or specified as "null", the first non-top window is selected. The top window is the one that would be selected by selectWindow() without providing a windowID . This should not be used when more than one popup window is in play.
Otherwise, the window will be looked up considering windowID as the following in order: 1) the "name" of the window, as specified to window.open(); 2) a javascript variable which is a reference to a window; and 3) the title of the window. This is the same ordered lookup performed by selectWindow .
I took slightly different approach which was to force any links to use target = _self so that they could be tested in the same window :
protected void testTextLink(WebDriver driver, final String linkText, final String targetPageTitle, final String targetPagePath) {
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement link = driver.findElement(By.linkText(linkText));
// ensure that link always opens in the current window
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('target', arguments[1]);", link, "_self");
link.click();
wait.until(ExpectedConditions.titleIs(targetPageTitle));
// check the target page has the expected title
assertEquals(driver.getTitle(), targetPageTitle);
// check the target page has path
assertTrue(driver.getCurrentUrl().contains(targetPagePath));
}
Simply use this code.
public void newtab(){
System.setProperty("webdriver.chrome.driver", "E:\\eclipse\\chromeDriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.w3schools.com/tags/att_a_target.asp");
//I have provided a sample link. Make sure that you have provided the correct link in the above line.
driver.findElement(By.className("tryitbtn")).click();
new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")), Keys.NUMPAD2).build().perform();
// In keyboard we will press
//ctrl+1 for 1st tab
//ctrl+2 for 2nd tab
//ctrl+3 for 3rd tab.
//Same action is written in the above code.
}
//Now you can verify the text by using testNG
Assert.assertTrue(condition);
In this Case we can use KeyPress
keyPress(locator, keySequence)
Arguments:
locator - an element locator
keySequence - Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". [Give for CTRL+T]
Simulates a user pressing and releasing a key.