How to take runtime input in selenium while automation testing? - selenium

I'm trying to take data from user at run time while automating a Webapplication. I have searched a lot but I couldn't find anything. I have tried this method. (code mentioned below)
Scanner scanner_user = new Scanner(System.in);
System.out.println("Enter your Email or Phone : ");
String user = scanner_user.nextLine();
System.out.println("our otp is " + user.toString());
but It doesn't work . it ask to enter data in console but it says read only view. please help me how can I take data at runtime.

You can use the below in this scenario user is passing the password manually through console.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String password;
System.out.println("Please Enter the user password :: ");
password= br.readLine();
driver.findElement(By.id("pwd")).sendKeys("password");

Related

Jsoup only fetches few lines of the HTML from start which is not even 25%

When i try to do CTRL+U on website then also its more then what i get from jsoup. The site am using is Open SAP -> https://open.sap.com/courses
Have tried timeout and maxbodysize along with jsoup.connect.
Right now my code looks like this:
private static String getHtml(String location) throws IOException {
URL url = new URL(location);
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String input;
StringBuilder builder = new StringBuilder();
while((input = in.readLine()) != null)
{
builder.append(input);
}
return builder.toString();
}
document = Jsoup.parse(getHtml(URL));
But still same HTML returned. By selenium its possible but it a bit slow so any other way to achieve this?
Because by aim is to find out the links of the courses and then load them to find their course summary which with selenium will be too slow.
Please suggest what can be done here.
The page content of this page is constructed inside your browser based on js. You need a framework with js support to do this.
Using HtmlUnit i got the page like this
String url = "https://open.sap.com/courses";
try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_68)) {
webClient.getOptions().setThrowExceptionOnScriptError(false);
HtmlPage page = webClient.getPage(url);
webClient.waitForBackgroundJavaScriptStartingBefore(10_000);
System.out.println("-------------------------------");
System.out.println(page.asText());
System.out.println("-------------------------------");
}
HtmlUnit has a rich API to do everything you like with the page object like searching for controls/content, clicking controls or extracting the text from parts of the page.

Open verification code sent in mail box then copy this code and paste it into verification code field in selenium testing

I am new to selenium web testing i have automated a Sign-In process for a web base application. now making it for Sign Up process i am stuck at a point where a verification code is sent to a mail address and then i have to copy that into my verification code field and proceed further
As i have searched so far i came to know about the mailosaur server but unable to copy that email verification code into my automated web browser. i also searched for the tutorials but unable to find any useful resource. also i want to generate random emails that part is also not getting in my mind.
As i am new to selenium so it is requested to please provide detail answer so i can understand it better, Thanks in advance, working on Intellij, Mavaen (Java)
You can use mailinator.com. No need to register or create a mail box. In your app just enter email with made up name #mailinator.com (asad1#mailinator.com, asadXY#mailinator.com, whatever).
To collect confirmation link (double opt in) I'm using this:
public class Mailinator {
public WebDriver driver;
public Mailinator(WebDriver driver) {this.driver = driver;}
public String urlMailinator = "https://www.mailinator.com/";
public WebDriverWait waitSec(WebDriver driver, int sec) {return new WebDriverWait(driver, sec);}
public static String doubleOptInLink = null;
public String getDoubleOptInLink() {return doubleOptInLink;}
public void setDoubleOptInLink (String doubleOptInLink) {Mailinator.doubleOptInLink = doubleOptInLink;}
public void collectDoubleOptInLink(String userEmail, int expectedNumberOfDeliveredEmails) throws InterruptedException {
driver.get(urlMailinator);
WebElement fldInbox = waitSec(driver, 5).until(ExpectedConditions.elementToBeClickable(By.id("inboxfield")));
fldInbox.sendKeys(userEmail);
WebElement btnGo = driver.findElement(By.xpath("/html/body/section[1]/div/div[3]/div[2]/div[2]/div[1]/span/button"));
btnGo.click();
waitSec(driver, 600).until(ExpectedConditions.numberOfElementsToBe((By.xpath("//*[#id=\"inboxpane\"]/div/div/div/table/tbody/tr")), expectedNumberOfDeliveredEmails));
WebElement lastMailLink = driver.findElement(By.xpath("//*[#id=\"inboxpane\"]/div/div/div/table/tbody/tr"));
lastMailLink.click();
Thread.sleep(3000);
driver.switchTo().frame(driver.findElement(By.id("msg_body")));
setDoubleOptInLink(driver.findElement(By.xpath("//*[#id=\"intro\"]/tbody/tr/td/a")).getAttribute("href"));
}
}
In my scenario:
register to webapp with new made up email, confirmation email is send
using collectDoubleOptInLink(email, 1); is the confirmation link set as doubleOptInLink
calling another method to go to the confirmation link with getDoubleOptInLink();
Sure you will need change what string comes to setDoubleOptInLink();
In specific cases don't forget to setDoubleOptInLink(null);.

How to Handle Authentication alert of browser in selenium webdriver?

Can anyone know that how can we handle Authenticate alert box of browser in selenium Webdriver ?
I user following code but its not working.
driver.switchTo().alert().authenticateUsing(new UserAndPassword("uname", "Password"));
Here is a screenshot of what I am trying to fill in:
Does anyone know how can I enter those credentials?
You can handle this in two ways:
You can pass the username and password directly through the URL like this:
driver..get("https://MyUserName:password#staging.www.abc.com")
You can also use AutoIT Tool for handling any kind of window popups.
For this you first have to download and install AutoIt
Then download SciTE4AutoIt3
You can do scripting in it, or you can use Au3Recorder. It is not available in new versions of SciTE, but you can download it from old versions separately. Unzip it and copy:
autoit-v3.3.14.0.zip\install\Extras\Au3Record
to
[#Install Dir of AutoIt in Program files]\Extras\Au3Record
Now you can start the recorder directly by clicking Au3Record.exe or you can find it in the Script Editor window Tools >AU3Recorder.
For it you have to create a blank .au3 file in the Script Editor. Now start recording. Perform action on Window Popup. Stop when Done. Save it with .au3 format.
Now GO to Saved File location >> Right Click on the File and compile it (Compile Script(x64) or else). It will create an .exe file in the same folder.Now run that script in your Project using:
Runtime.getRuntime().exec("File Loaction/MyAutoItScript.exe");
It will work.
Try below code:
String username = "myUsername";
String password = "myPassword";
String URL = "http://" + username + ":" + password + "#" + sso.mywebsite.com/usdf/ls/dia?kkkk;
driver.get(URL); // Basically operation done here itself still if not work use further Alert code as well
Alert alert = driver.switchTo().alert();
alert.accept();
Full code will be like:
driver.get("https://sso.mywebsite.com/usdf/ls/dia?kkkk");
String url = driver.getCurrentUrl().replaceAll("https://", "");
String username = "myUsername";
String password = "myPassword";
String URL = "https://" + username + ":" + password + "#" + url;
driver.get(URL); // Basically operation done here itself still if not work use further Alert code as well
Alert alert = driver.switchTo().alert();
alert.accept();
Note : Even alert code do not required .. use it as it works for you and this code works on chrome better
Something like this?
driver.Navigate().to("http://UserName:Password#url.‌​com")
or
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(*username*, *password*));
I use Java for my test automation. I have searched for a decent way to deal with these sign in pop ups and cannot find one. The most common answers are either to include in a URL as prefix prior to the real url (eg https:\username:password#www.website.com) or to use a wait for alert. These have not worked for me as: on a form submit there is no simple url to use and I am not sure as to the security including the password in the start of the url; with the wait for alert the webdriver hangs until there is a response - which only comes from submitting the login response via the pop up.
The workaround I have found is poor - I've not got it to work in a headless environment and so limits this answers usefulness. Would be great to get a real answer here. Note that I am running this in a Windows environment and if I was using Linux I have read that I could use xvfb to provide a 'screen' for sikuli and then this would work - if anyone can comment on how to do this on a Windows server that would be MUCH appreciated.
I use Sikuli for the automation of things I cannot automate via Selenium. Sikuli does many things, including letting you basically feed it images that it performs actions on.
For this purpose I run Sikuli on a thread started prior to clickin the submit that leads to the sign in pop-up. As it is running on a different thread it doesn't block the main thread, so it can still execute the log in. Once it logs in it shuts down and logging in closes the pop up and reactivates the main thread.
Specifically:
Sikuli MAVEN entry for POM:
<dependency>
<groupId>com.sikulix</groupId>
<artifactId>sikulixapi</artifactId>
<version>1.1.4-20191010.160947-268</version>
</dependency>
In the main code use a runnable executed via an executor:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
private final AtomicInteger expectedResultCount;
private final AtomicInteger publishedResultCount;
private final ExecutorService executor;
ExecutorService executor = Executors.newFixedThreadPool(5);
String processName = "asic-login";
LoginPopUp login = new LoginPopUp(this, processName);
addResultExpectation(processName);
executor.execute(login);
The runnable here implements an interface I use to keep things tidy:
The main class implements the interface to manage the threads:
public class TestRunner implements ResultPublisher{
These are functions inside the main class for thread management:
private void addResultExpectation(String process){
resultMap.put(process, new JSONObject());
expectedResultCount.addAndGet(1);
}
public void publishResult(JSONObject result){
String process = result.getString("process-name");
String strResult = result.getString("result");
resultMap.put(process, result);
publishedResultCount.addAndGet(1);
if(publishedResultCount.get() == expectedResultCount.get()){
executor.shutdown();
System.out.println("shutting down executor for run " + runId);
}
}
This is the interface
import org.json.JSONObject;
public interface ResultPublisher {
void publishResult(JSONObject result);
}
This is the runnable Runnable - an inner class in the TestRunner main class:
private class LoginPopUp implements Runnable{
private ResultPublisher publisher;
private String filePath;
private String processName;
private LoginPopUp(){
}
public LoginPopUp(ResultPublisher publisher, String processName){
this.publisher = publisher;
this.processName = processName;
}
private void publish(JSONObject result){
publisher.publishResult(result);
}
public void run(){
JSONObject result = new JSONObject();
result.put("path", filePath);
try{
Screen sd = new Screen();
ScreenUtility s = new ScreenUtility(imagesDirectory);
s.clickImage("LoginTitle.PNG", 10, 2500);
s.typeImageWithOffset("UserName.PNG", userName, 30,0);
s.typeImageWithOffset("Password.PNG",String.valueOf(password), 50,0);
s.clickImage("AsicSignIn.PNG", 10, 250);
}catch(Exception ex){
result.put("result", ex.getMessage());
result.put("process-name", processName);
publish(result);
Logger.getLogger(BCSRobot.class.getName()).log(Level.SEVERE, null, ex);
return;
}
result.put("result", "logged in successfully");
result.put("process-name", processName);
publish(result);
return;
}
}

Websdriver - sendKeys command is not typing on Password type field

I am trying to learn selenium webdriver automation but I am finding that the sendKeys command is not typing on Password type fields. I can see that some other people are also experiencing the same problem by googling it, but I haven't seen any correct answer yet. Could anyone please help me here.
Please find below sample code; I generated code from Selenium IDE and its working fine on IDE but not when I use webdriver.
package com.example.tests;
public class Login {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.webs.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testLogin() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.cssSelector("span")).click();
driver.findElement(By.id("FWloginUsername")).clear();
driver.findElement(By.id("FWloginUsername")).sendKeys("aug2qatestingqa#yahoo.com");
driver.findElement(By.id("FWloginPassword2")).clear();
driver.findElement(By.id("FWloginPassword2")).sendKeys("webs");
driver.findElement(By.id("sign_in_leaf")).click();
}
There were two password fields and one is hidden. Solution is to click on first password [hidden] field to get second password field enabled.
driver.findElement(By.id("FWloginUsername")).sendKeys("aug2qatestingqa#yahoo.com");
driver.findElement(By.id("FWloginPassword")).click();
driver.findElement(By.id("FWloginPassword2")).clear();
driver.findElement(By.id("FWloginPassword2")).sendKeys("webs");
I had almost a similar situation for Password field. There were two elements for the same 'Password' field but with different IDs. The JavaScript was toggling "type = password" on run time for a click, clear or any action to this field.
Solution in this case is to find the text with input type = password,
for example:
driver.FindElement(By.CssSelector("input[type='password']")).SendKeys(IWebElement);
My problem was that I used ActionChains which caused the later fields not being filled when using send_keys method.
The solution was to call actions.reset_actions()
e.g.
actions = ActionChains(driver)
actions.key_down(Keys.LEFT_CONTROL).send_keys("a").perform()
actions.key_down(Keys.LEFT_CONTROL).send_keys("c").perform()
actions.reset_actions()
# now send_keys() method works again
cvvTxtBox().sendKeys("1234");
cvvTxtBox().sendKeys(Keys.TAB);
Final Solution on this problem.
Else use Robot

Having problems when trying to login to a website using C++/cli

I've been roughly searching over the internet for some answers to my problem, but I still couldn't figure out how to log in to a website properly.
Firstly, I'm going to explain what I've done until this moment.
» I opened this website: http://side.utad.pt/cursos/einformatica/ upon which I want to log in.
» After opening its souce code, I found the Url that the Login form posts to is:
https://side.utad.pt/side-secure3/login.pl
I tried to open it but an Internal Error came out so I tried to access that url without /login.pl instead but i don't have permission to. As I can't get this Url working, I thought about using the first link itself.
» By using tamper data extension(Firefox) I found that there are 3 post arguments: sessionid, username and password. Username and password are input by the user himself.
To get sessionid, I simply searched for it inside source code and took it from there:
String^ formUrl = "http://side.utad.pt/cursos/einformatica/";
String^ pageSource;
WebClient^ client = gcnew WebClient();
pageSource = client->DownloadString(formUrl);
delete client;
client = nullptr;int index = pageSource->IndexOf("sessionid");
int startIndex = index + 34;
String^ _sessionid = pageSource->Substring(startIndex, 32);
Until here, everything was fine apart from the Url problem.
» Started formatting all the data gathered(which I believe is the correct way):
String^ formParams;
// format data
formParams = "sessionid="+ _sessionid+"&username="+username+"&password="+password;
» After that, I started working with the "body" of the code:
WebRequest^ req = WebRequest::Create(formUrl);
// encode our data
array<Byte>^ bytes = System::Text::Encoding::ASCII->GetBytes(formParams);
req->ContentType = "application/x-www-form-urlencoded";
req->Method = "POST";
req->ContentLength = bytes->Length;
Stream^ os = req->GetRequestStream();
os->Write(bytes,0,bytes->Length);
os->Close();
Am I doing it correctly until here?
» I wanted to check if i'm logged in or not, so I thought about getting another source code, but this time on pos-login page(can be accessed without logging in but we're always carried to that page after logging in):
// this code is added below os->Close();
WebResponse^ resp = req->GetResponse();
String^ cookieHeader;
cookieHeader = resp->Headers["Set-cookie"];
WebRequest^ getRequest = WebRequest::Create("http://side.utad.pt/cursos/einformatica/principal"); // Exception 1
getRequest->Headers->Add("Cookie", cookieHeader);
WebResponse^ getResponse = getRequest->GetResponse();
StreamReader^ sr = gcnew StreamReader(getRequest->GetRequestStream()); // Exception 2
pageSource = ""; // reset
pageSource = sr->ReadToEnd();
Firstly, the first line does raise an exception - most of the times - but I don't know the cause: 'The server commited a protocol violation Section=ResponseStatusLine'
Secondly and lastly, when that line doesn't raise an exception, this does(cannot send a content-body with this verb-type)
StreamReader^ sr = gcnew StreamReader(getRequest->GetRequestStream());
Any ideas to get this working?
I think that the problem here is related to the cookies. I might have not saved them properly..
Thanks