FindElementsBy id for username and password - selenium

I've started learning selenium web driver. I've come across an issue. When I navigate to my URI, I come across an windows authentication window before I can access my web page. Im using C# for the scripting. Ive got the code that I should be using:
// Get the page elements
var userNameField = driver.FindElementById("usr");
var userPasswordField = driver.FindElementById("pwd");
var loginButton = driver.FindElementByXPath("//input[#value='Login']");
// Type user name and password
userNameField.SendKeys("admin");
userPasswordField.SendKeys("12345");
But this is only good if you have a normal login page. I can't get to the elements or get the Fire Path id as the window authentication pop will not let me. Can someone please help me with this. How do I automate this process
Thanks

We have a way to handle this by passing username and password inside URL like the following:
driver.Navigate().GoToUrl(https://<username>:<password>#<URL>");
e.g.
driver.Navigate().GoToUrl(https://auth_user1:userpassword1#www.google.com");
Hope this helps!

Related

Logging into eBay Using VB Web Browser

I have been trying to login to eBay through the web browser module in vb but I am struggling to find a way to fill in the boxes by using the click of a button. I have tried this by using the GetElementById as follows:
If InStr(TextBox1.Text, "EQP") Then
WebBrowser1.Document.GetElementById("1560960309").InnerText = "username" ' Username
WebBrowser1.Document.GetElementById("1605523682").InnerText = "password" ' Password
WebBrowser1.Document.GetElementById("sgnBt").InvokeMember("click") ' Click Login Button
This code doesn't do anything at all but has worked using other websites, before the eBay ID's used to be simple and I am now finding that these IDs seems to change in each session.
Any help would be great.
Thanks! :)
I believe you cant do this like you can on other websites as Ebay is trying to put a block on all ways of phishing. However Ebay does have an API for .NET that you should be able to use and in the long run it will look and feel much better. Here is the link : https://go.developer.ebay.com/netsdk
Hopefully this leads you in the right direction.
Good Luck!

How to communicate PHP with PhantomJS for solving Captchas

The problem I'd like to solve is the following:
I need to manage an external web page through PHP, for example, login and then change the profile info on the external web after sending an ajax request on my own web.
For this, I'm calling PhantomJS from PHP to do those tasks, but before login to the external web I need to fill the captcha input. So, I'd like to send back the Captcha image to my web, write the correct code and send it back to the WebPage module of PhantomJS to login using that code.
In other words, I need a 'syncronous' program like this:
1) PHP -> Send a request to login and obtain the captcha image.
2) PhantomJS -> Open a WebPage instance and render the captcha code to an image.
3) PHP -> Get the captcha image, show it to an user and send a text input to PhantomJS.
4) PhantomJS -> Get the text code from PHP, fill the captcha input using 'page.evaluate' and login. Send to PHP some data ('Login successfull', 'Login failed', etc)
5) PHP -> Get the callback and send another task or data.
callback = 'Login successfull' --> Change profile picture or update user info.
callback = 'Login failed' --> Try to login again (like point 1)
Etc...
There are many things I don't know how to handle. For example:
1) How could I keep the WebPage module open and waiting for the text code of the captcha? If I close it, a new captcha code will appear next time, and I need a way to wait the code and get it. Do I need to start a server for this?
2)Get the captcha image from PHP isn't a problem (because of 'page.render'), but how I could send a text back to the WebPage instance of PhantomJS? I think is better to send data bidirectionally between both systems. Again, do I need a server?
I think I need a socket server in PhantomJS (how can this be done?). This server should have the WebPage instance that I need to keep open, but I'm not completely sure about this.
Thanks.
I recently published a project that gives PHP access to a browser. Get it here: https://github.com/merlinthemagic/MTS, Under the hood is an instance of PhantomJS.
The main issue is keeping a resource alive after initial execution. Here is how i propose you do it.
After downloading and setup you would simply use the following code:
Start of "Setup" session:
if (isset($_POST['sessionUID']) === false) {
//set the execution timeout long enough to cover the entire process (setup and working time), it dictates when phantomJS shuts down automatically.
ini_set('max_execution_time', 300);
//open the login page:
$myUrl = "http://www.example.com";
$browserObj = \MTS\Factories::getDevices()->getLocalHost()->getBrowser('phantomjs');
//allow the page to live after php shuts down.
$browserObj->setKeepalive(true);
$windowObj = $browserObj->getNewWindow($myUrl);
//find the username input box, here it has id=username
$windowObj->mouseEventOnElement("[id=username]", 'leftclick');
//type your username
$windowObj->sendKeyPresses("yourUsername");
//find the password input box, here it has id=passwd
$windowObj->mouseEventOnElement("[id=passwd]", 'leftclick');
//type your password
$windowObj->sendKeyPresses("yourPassword");
//click on the login button, here it has id=login
$windowObj->mouseEventOnElement("[id=login]", 'leftclick');
//i assume this is when you encounter the CAPTCHA image
//find the CAPTCHA image element, here it has id=captchaImage
$element = $windowObj->getElement("[id=captchaImage]");
$loc = $element['location'];
//tell the screenshot to only get the CAPTCHA image
$windowObj->setRasterSize($loc['top'], $loc['left'], ($loc['right'] - $loc['left']), ($loc['bottom'] - $loc['top']));
$imageData = $windowObj->screenshot("png");
$sessionUID = uniqid();
$saveWindowObj = serialize($windowObj);
//save the window object so we can pick it up again
file_put_contents("/tmp/" . $sessionUID, $saveWindowObj);
}
//now render the CAPTCHA image to the user as part of a form they can resubmit and make sure to keep the $sessionUId as a hidden variable in the form on the page
End of the "Setup" session, php shuts down here.
Start of "Working" session:
We assume the user submits the form and it is a post containing the $sessionUID and the text string for CAPTCHA.
if (isset($_POST['sessionUID']) === true && isset($_POST['captchaTxt']) === true) {
$savedWindow = file_get_contents("/tmp/" . $sessionUID);
//delete the saved object
unlink("/tmp/" . $sessionUID);
//bring back the object to life
$windowObj = unserialize($savedWindow);
//make sure the browser is now shutdown on exit
$windowObj->getBrowser()->setKeepalive(false);
//find the CAPTCHA input box, here it has id=captchaInput
$windowObj->mouseEventOnElement("[id=captchaInput]", 'leftclick');
//type the CAPTCHA string
$windowObj->sendKeyPresses($_POST['captchaTxt']);
//click on the button to accept CAPTCHA, here it has id=captchaOK
$windowObj->mouseEventOnElement("[id=captchaOK]", 'leftclick');
//now use the clickElement() etc functions on $windowObj to do what you need to do.
}
End of the "Working" session, php shuts down here.

Windows 8 Metro Show Webview in Popup and pass response back OAUTH2 Visual Basic

This is my first question so hello and thanks for your support!
I am currently developing a windows 8 store app.
I need to login to an OAUTH website and get the response token to save as a string.
I would like this to appear in a popup, have the user login, then close once a response is received.
I can get the webview to pop up and I can navigate to the page. But how do i handle the response and close. I speak VB.
Thanks again!
Edited to add my code:
Dim url As New Uri("https://aurlthatidontcontrol")
WebView1.Navigate(url)
PopUp.IsOpen = True
MY popup opens and the login for the url is presented.
Once I log in I should get a response from that server which includes an access token
I want to get that token into my app and save it as a string, then close the popup
Ok I figure it out.
Instead of actually calling a webview I used the web-broker authentication. Details
This allows the service login to "pop" on the screen and I can capture the result like this:
Dim webresult As WebAuthenticationResult = Await
WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartURI, endURI)
Dim finalresponse() As String = webresult.ResponseData.ToString.Split("=")
Dim currentuserstoken As String = finalresponse(1)
Return currentuserstoken
Use the InvokeScript method on the WebView class to call JavaScript code to collect information from the response and return it the calling code. If there is no script in the page you control, use "eval" as the function name and pass arguments to it.
Alternatively, use window.external.notify in JavaScript to fire the ScriptNotify event (link includes an example).

Facebook Connect: User has logged in and given permissions, now what?

So i've been trying to get FB Connect working on my site, simply for login and authentication, using the Javascript SDK and following the code at:
https://developers.facebook.com/docs/guides/web/
So the button appears, i click it, a dialog pops up, i click that, presumably my site now has permission to know who i am...
Then what? The guide goes on to saying all the stuff I can access through the Facebook API, all the cool things about permissions, but presumably i need the user's ID or access token or something to get at this stuff. How is that given to me? left as a attribute on one of the elements? Left in a Javascript variable somewhere? Given as an argument to some callback? Thrown high into the heavens for me to receive via satellite downlink?
This is probably incredibly simple, but for the life of me i have not been able to figure it out. Facebook's tutorials have failed me, and so has Google. I want to get this in the Javascript, so I can immediately fill in form-data using the user's Facebook name, put a picture, etc. etc., and presumably send this all back to the server so the server can validate with Facebook that the data is real.
I'm assuming you're using the Login button? https://developers.facebook.com/docs/reference/plugins/login/
If you simply want form info, check out the registration plugin - https://developers.facebook.com/docs/plugins/registration/
However, to answer your question, make an API call to /me. For example:
FB.api('/me', function(user) {
if(user != null) {
// The user object now contains info about the logged in user
}
});
You should subscribe to the auth.login event and wrap the above API call in the successful response, i.e.:
FB.Event.subscribe('auth.login', function() {
// JS to run if when the user logs in, for example, the code snippet above
});

Login check using HtmlUnit

Hy... i want to login to some 3rd party sites using HtmlUnit. But HtmlUnit should be able to tell me whether the login attempt to the input site is successful or not. Is there any way around to perform this task using HtmlUnit. Please help ..!!!
Thanks
Usman Raza
I'm currently using HTMLunit to log in to a site that has a varification page and redirect. some of my code for this is:
//---------------------------------Login Page---------------------------------
HtmlPage PageLogin = webClient.getPage(url);
HtmlElement submitButton = (HtmlElement) PageLogin.getByXPath(Xpath To Button).get(0);
HtmlTextInput name = (HtmlTextInput) PageLogin.getElementById("UserIdInput");
HtmlPasswordInput pass = (HtmlPasswordInput)PageLogin.getElementById("ADloginPasswordInput");
name.setText(username);
pass.setText(password);
System.out.println("Logging in to site");
//------------------------------------------------------------------------
//---------------------------------Pass varified Page----------------------
HtmlPage pagePassVarified = submitButton.click();
System.out.println("Successfully Logged in to site");
HtmlElement btnContinue = (HtmlElement) pagePassVarified.getElementById("BtnClickToContinue");
//---------------------------------------------------------
//---------------------Home Page----------------------------------
HtmlPage pageHome = btnContinue.click();
System.out.println("Home Page accessed");
//----------------------------------------------------------------
This code goes to a login page, adds username and passwords to text boxes, and clicks the submit button. We are next redirected to a "wait 5 seconds, or click here to continue to home page" type of page, where the continue button is clicked. Lastly we arrive at our home page that we wanted to log into. I selected the page elements by both ID and Xpath when no ID was available.
You can have HtmlUnit check the URL, or search for a specific element on the page, more precisely one you know to be present only in one case (sucessful login / rejected).
Like RabidFX suggested, I would suggest you to check URL but in some cases (I've seen such situations in my work experience) URL may still the same. Then, my suggestion would be checking for a specific element and it should be the login form because generally unsuccessfull login attemps redirect you to the same page that has the same login form. That would not be hard - coded solution because I hope you have found some way to get that login form with a generic way :)