Basic Autthentication in Selenium without choosing an element - selenium

I need to log in to a popup window and I tested every method proposed by people and none of them worked! So what I am trying to do is to simply go to a url and promptly type the username\t and password and hit the Enter. Normally this can be done by choosing that input element, but not in this case. How can I type without choosing the element?

This is what I've tried and has worked for me in the past.
System.Windows.Forms.SendKeys.SendWait("UserNoome");
System.Windows.Forms.SendKeys.SendWait({TAB});
System.Windows.Forms.SendKeys.SendWait("Passwoord");

Assuming the focus is on the frame. Try using Actions for the needful [code in java] :
Actions action = new Actions(webdriver); //replace with your driver
action.sendKeys("username").perform();
action.sendKeys("\t").perform(); //possibly Keys.TAB
action.sendKeys("password").perform();
action.sendKeys("\n").perform(); //possibly Keys.ENTER
Edit : Also keyDown(Keys.TAB) could be used as an alternate to sendKeys("\t")

Related

instead of sendkeys last copied item from clipboard is getting entered in the element

In my application I have an email field and I'm using sendkeys to send an email address, but instead of sendkeys selenium inserts the value from clipboard. Do anyone faced this issue?
code:
WebElement email=driver.findElement(By.xpath("//div[#class='auth-container']//input[#type='text']");
email.sendKeys("sample#sample.com")
since Id is dynamic I have taken xpath from parent container
In Node.js javascript, on hungarian keyboard, the # sign in sendKeys has replaced with the content of clipboard. If you try to replace "#" width its unicode value "\u0040", the result is same, the sendKeys has has replaced with the content of clipboard, even though try to the tricky Key.chord( Key.ALT, "v", Key.NULL ) form, it does nothing.
// if clipboard contains XXX
WebElement email=driver.findElement(By.xpath("//div[#class='auth-container']//input[#type='text']");
email.sendKeys("sample#sample.com")
// result: field content is sampleXXXsample.com
If you put # sign on the clipboard, it works well, but you cant guarantee the content of clipboard in test automation. There is a way, to send keys to the active item.
I would avoid to fill the field with javascript, as mentioned above, because javascript fill it directly, does not care with the field status, fill it with value even though the field is inactive, do not triggers events, etc, javascript is brute force fill the field.
Send. Keys. There is a npm package for it. It is a wrapper for powershell sendkeys, so works only on windows.
npm install -g sendkeys
and the test code:
const sendkeys = require( 'sendkeys');
WebElement email=driver.findElement(By.xpath("//div[#class='auth-container']//input[#type='text']");
email.sendKeys("sample")
// result: cursor is in the field, field contains 'sample'
sendkeys.sync( "#sample.com" )
// result: field content is 'sample#sample.com'
If send keys is not working try using action chains. It is often a good way to solve selenium interaction problems.
from selenium.webdriver.common.action_chains import ActionChains
action = ActionChains(driver)
email = driver.find_element_by_xpath("//div[#class='auth-container']//input[#type='text']"))
action.send_keys_to_element(email, "sample#sample.com").perform()
hope this helps
I am run script in java, hope this help you..
Using javascript I successfully send data into textbox.
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('identifierId').value='admin'");
Another way :-
WebElement Username = driver.findElement(By.xpath("//*[#id=\"identifierId\"]"));
((JavascriptExecutor)driver).executeAsyncScript("arguments[0].value='admin'",Username);
Here we are passing WebElement as a argument to the javaScript.
For more information refer this link
Another way is using robot class ..Common solution is to use the clipboard, Copy text and paste that text into text field.
String username = "admin";
StringSelection stringSelection = new StringSelection(username);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
This doesn't type the entire "string" but helps to type whatever you want other than one character at a time.
String un="admin";
char c;
int l=un.length(),v1=0,v2=0;
//System.out.println(l);
while(v1<l)
{
c=un.charAt(v1);
v2=(int) c; //converts character to Unicode.
robot.keyPress(KeyEvent.getExtendedKeyCodeForChar(v2));
Thread.sleep(150);
robot.keyRelease(KeyEvent.getExtendedKeyCodeForChar(v2));
v1++;
}
see it works perfectly and it's awesome! Though it doesn't work for special characters which cannot be traced by unicode like |,!...etc.
I have encountered this, but it seemed to be intermittent. The code that was working well for months, suddenly doing the same thing (pasting from clipboard in place of every # aka "at sign" ).
I was able to make it go away (won't say "fix") by updating Chromedriver. I suspect that this was because Chrome has auto-updated, but the Chromedriver didn't. Can't be sure, because also had to reboot in the process.
In any case, this is not "normal". Email addresses with # sign should be passed through sendKeys without problems.
This works for me:
chromeoptions.AddUserProfilePreference("settings.language.current_input_method", "US");

How to handle the button click in Selenium Webdrive?

I am new to WebDriver,and currently trying to write the code to click the button. The locator is not available so I have used Xpath,but it is not working as it should be. Kindly help me on this.
Button tag:
<button onclick="myFunction()">Try it</button>
My web drive code:
drive_url.findElement(By.xpath("html/body/button")).click();
Did you check your xpath in browser console. You can check xpath by writing $x("<your xpath>") in console. Try using "//button" instead of what you're using now.
You should be little careful writng the selector as well. Try to avoid flaky selector and make is as unique as possible.
By xpath = By.xpath("//button[contains(text(),'Try it')]");
drive_url.findElement(xpath ).click();
The above selector finds the button tag explicitly using text based search.
Try this:
WebElement btn = driver.findElement(By.tagName("button"));
String btnText= driver.findElement(By.tagName("button")).getText();
if(btnText.equals("Try it")){
btn.click;
}

selenium (phpunit) click on drop down link

I want be able click on link from drop down using selenium with phpunit. I don't have any idea how make it happens, can anyone show me example or relevant tutorial, post or anything that can help me figure out.
when I try click on the element without put mouse over the drop down I got this error:
Element is not currently visible and so may not be interact with command ....
Thanks.
EDIT:
when I said "drop down" I don't mean regular select. it more like popup
you can see the example here:
http://investing.com
look how they build the menu I want be able click on 'Technical' -> 'Fibonacci Calculator' for example.
Check this post out:
Selenium: How to select an option from a select menu?
You can find more info about this here
select(selectLocator, optionLocator)
Arguments:
selectLocator - an element locator identifying a drop-down menu
optionLocator - an option locator (a label by default)
Select an option from a drop-down using an option locator.
Option locators provide different ways of specifying options of an HTML Select element (e.g. for selecting a specific option, or for asserting that the selected option satisfies a specification). There are several forms of Select Option Locator.
label=labelPattern: matches options based on their labels, i.e. the visible text. (This is the default.)
label=regexp:^[Oo]ther
value=valuePattern: matches options based on their values.
value=other
id=id: matches options based on their ids.
id=option1
index=index: matches an option based on its index (offset from zero).
index=2
If no option locator prefix is provided, the default behaviour is to match on label.
Credits go to Dave Hunt
What I use:
$search13 = $this->webDriver->findElement(WebDriverBy::id('id_of_dropdown_field'));
$search13->click(); // Clicking on the dropdownfield
$this->webDriver->getKeyboard()->pressKey('ARROW_DOWN'); // Will go down in your dropdown selection )
sleep(1);
$this->webDriver->getKeyboard()->pressKey('ENTER'); // Enter for submitting your selection
EDIT:
http://www.anitpatel.net/2012/02/25/selenium-webdriver-how-to-click-on-a-hidden-link-or-menu/
This one explains it in java but basically what he does is a mouse over/hover and wait.
Then he clicks on the element.
I'm not a java genius but it's an example how to work with it.
You can use the:
string mouseOver(string $locator)
This simulates a user hovering a mouse over the specified element.
http://docs.tadiavo.com/phpunit/www.phpunit.de/pocket_guide/3.1/en/selenium.html
Check if the element is visible using the xpath of the required option value.
$this->isElementPresent($xpath);
$this->click($xpath);
If it is true, then click() method selects the specified option.

How to foucs a new window (third party without windowName) in selenium IDE?

I am submitting search criteria through form to third party URL. I tried to give target="someName". But when i am trying to focus on new window using "sameName" and validating some text there, selenium unable to find that locator or focus on that window. retuning false. please help on this. its urgent.
I also tried storeAllWindowNames or Ids selenium commands, also not working its returning main window ID instead of new open window.
the idea is in the following. as you try to validate some text in a new window, I do not see any necessity to get window name as you are able to get the xpath or cssselector of the text to be validated using firepath (firebug addon in ffox) and using command
String txt = driver.findElement(By.xpath(//...blablbalba)).getText().trim();
//or
String txt = driver.findElement(cssSelecot(html>..blalblabla...)).getText().trim();
//validation
Assert.assertTrue(txt.equals("blablabla"));
you can actually validate it.
or if you want to validate something and selenium is not able to cope with it then I recommend you to use js (getText using js):
String cssSelector=....
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x = $(\""+cssSelector+"\");");
stringBuilder.append("return x.text().toString();") ;
String res= (String) js.executeScript(stringBuilder.toString());
Assert.assertTrue(res.trim().contains("blablabla....") );
Hope this works for you.
This is the solution:
Well, if you have no choice but use it. Here is one solution:
if you have a target with your own name like target="popup", then you only need open the target window before click on the link. Example:
[b]store "javascript{selenium.browserbot.getCurrentWindow().open('', 'popup')}", "myWindow"[/b]
If you have a target="_blank", you need change the target before open the window.
store "javascript{this.page().findElement('link=My link who open the popup with target blank').target='popup'}", "myVar"
store "javascript{selenium.browserbot.getCurrentWindow().open('', 'popup')}", "myWindow"
Then, you click on the link and selectWindow("popup"). That is.
Another solution is rewrite the entire A tag and change the href/target by a javascript window.open but this is a litle more work to do.

Simulate TAB keypress event in Selenium RC

I need to simulate a tab keypress in Selenium RC, using the Java API.
I do this after having entered some text using:
selenium.type(input, "mytext");
I've tried 3 alternatives to get the tab working:
selenium.keyPress(input, "\\9");
and:
selenium.focus(input);
selenium.keyPressNative("09");
and even:
selenium.getEval("var evt = window.document.createEvent('KeyboardEvent');evt.initKeyEvent ('keypress', true, true, window,0, 0, 0, 0,0, 9,0);window.document.getElementsByTagName('input')[2].dispatchEvent(evt);")
The best I can get is a "tab space" to be inserted after my text so I end up with this in the input field:
"mytext "
What I actually want is to tab to the next control. Any clues? Thanks!
(Note: I have to use tab and can not use focus or select to chose the element I want to go to, for various reasons, so no suggestions along these lines please!)
selenium.keyPressNative(java.awt.event.KeyEvent.VK_TAB + "");
I don't use the Java API, but this post from google groups suggests it is your solution. I can't imagine that "9" is different from "09" in your question, but give it a try?
Try the official TAB char: \t or \u0009
Some functions may used Onblur. It will trigger the function when the field lose the key focus. here we can use fireEvent with "blur" or "focus" command as follows:
command: fireEvent
target: id=your_field_identification
value: blur
Reference: http://qaselenium.blogspot.com/2011/01/how-to-triger-tab-key-in-selenium.html
Improvising Ryley's answer, we can use
selenium.keyDownNative(java.awt.event.KeyEvent.VK_TAB + "");
selenium.keyUpNative(java.awt.event.KeyEvent.VK_TAB + "");
I tried this method for VK_CONTROL in IE and it worked good.
Use typeKeys():
Quoting the above link:
Unlike the simple "type" command, which forces the specified value into the page directly, this command may or may not have any visible effect, even in cases where typing keys would normally have a visible effect. For example, if you use "typeKeys" on a form element, you may or may not see the results of what you typed in the field.
In some cases, you may need to use the simple "type" command to set the value of the field and then the "typeKeys" command to send the keystroke events corresponding to what you just typed.