how do I make Selenium webdriver to read a csv file to perform an action - selenium-webdriver

how do I make Selenium webdriver to read a csv file to perform an action. I have my script to load it in the browser and perform an action how do I make it to read csv file and replace that action with the data in the csv file

The best way to do this would be to use another library that specializes in such parsing, and feed it into memory. A good StackOverflow question regarding this is here.

Remember that WebDriver simply interacts with a browser. It's the language that your writing in that does file IO. I'd suggest creating a CSV class. Since csv is just a text file, you can read it in as a string and iterate through each line. Split by commas and you're good to go. You didn't specify a language so here is an example in C# from our library. Notice I use yield for efficiency. This was something I found somewhere. No need to reinvent the wheel.
public static class CSV
{
private static bool ignoreFirstLineDefault = false;
public static IEnumerable<IList<string>> FromFile(string fileName)
{
foreach (IList<string> item in FromFile(fileName, ignoreFirstLineDefault)) yield return item;
}
public static IEnumerable<IList<string>> FromFile(string fileName, bool ignoreFirstLine)
{
using (StreamReader rdr = new StreamReader(fileName))
{
foreach (IList<string> item in FromReader(rdr, ignoreFirstLine)) yield return item;
}
}
public static IEnumerable<IList<string>> FromStream(Stream csv)
{
foreach (IList<string> item in FromStream(csv, ignoreFirstLineDefault)) yield return item;
}
public static IEnumerable<IList<string>> FromStream(Stream csv, bool ignoreFirstLine)
{
using (var rdr = new StreamReader(csv))
{
foreach (IList<string> item in FromReader(rdr, ignoreFirstLine)) yield return item;
}
}
public static IEnumerable<IList<string>> FromReader(TextReader csv)
{
//Probably should have used TextReader instead of StreamReader
foreach (IList<string> item in FromReader(csv, ignoreFirstLineDefault)) yield return item;
}
public static IEnumerable<IList<string>> FromReader(TextReader csv, bool ignoreFirstLine)
{
if (ignoreFirstLine) csv.ReadLine();
IList<string> result = new List<string>();
StringBuilder curValue = new StringBuilder();
char c;
c = (char)csv.Read();
while (csv.Peek() != -1)
{
switch (c)
{
case ',': //empty field
result.Add("");
c = (char)csv.Read();
break;
case '"': //qualified text
case '\'':
char q = c;
c = (char)csv.Read();
bool inQuotes = true;
while (inQuotes && csv.Peek() != -1)
{
if (c == q)
{
c = (char)csv.Read();
if (c != q)
inQuotes = false;
}
if (inQuotes)
{
curValue.Append(c);
c = (char)csv.Read();
}
}
result.Add(curValue.ToString());
curValue = new StringBuilder();
if (c == ',') c = (char)csv.Read(); // either ',', newline, or endofstream
break;
case '\n': //end of the record
case '\r':
//potential bug here depending on what your line breaks look like
if (result.Count > 0) // don't return empty records
{
yield return result;
result = new List<string>();
}
c = (char)csv.Read();
break;
default: //normal unqualified text
while (c != ',' && c != '\r' && c != '\n' && csv.Peek() != -1)
{
curValue.Append(c);
c = (char)csv.Read();
}
result.Add(curValue.ToString());
curValue = new StringBuilder();
if (c == ',') c = (char)csv.Read(); //either ',', newline, or endofstream
break;
}
}
if (curValue.Length > 0) //potential bug: I don't want to skip on a empty column in the last record if a caller really expects it to be there
result.Add(curValue.ToString());
if (result.Count > 0)
yield return result;
}
}

I suggest you to use Excel files instead of csv. limitation while using CSV is when you want to use the delimiter ',' in the data itself e.g. if you you have an address field say Gyandeep Colony, B. No : - 1/5 here the ',' make break your code.
The way i do reading of data is by using my Utility Code
public class ExcelHandler {
public static String getSheetData(String path,String sheetName, int col , int row) {
Workbook workbook;
String data = null;
try {
workbook = Workbook.getWorkbook(new File(path));
Sheet sheet = workbook.getSheet(sheetName);
data = sheet.getCell(row,col).getContents();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public static String getSheetData(String path, int sheetNo, int col , int row) {
Workbook workbook;
String data = null;
try {
workbook = Workbook.getWorkbook(new File(path));
Sheet sheet = workbook.getSheet(sheetNo);
data = sheet.getCell(row,col).getContents();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
I just call these method wherever i want in my code .
Lets take an example
WebElement username = driver.findElement(By.id("username"));
username.sendKeys(Utility.getSheetData("Login.xls",0,1,0));
Happy Coding :)

FileInputStream file = new FileInputStream(new File("C:\\testdata.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
for (int i=1; i <= sheet.getLastRowNum(); i++){
String keyword = sheet.getRow(i).getCell(0).getStringCellValue();
searchbox.sendKeys(keyword);
searchbox.submit();
driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
}
workbook.close();
file.close();

Related

Encode InputStream response as UTF-8

I'm trying to make a connection to a URL which displays some data in plain text on a webpage (it's a block of text in between <pre> tags). Whenever a character with a character with a special character is passed through (for example é or ì) it displays a question mark instead of the character a �
is displayed. I've tried using this but that didn't change much. I can't read the page per line so I'm pretty much stuck here.
Here is my code:
try
{
// Open the connection
NetworkManager networkManager = NetworkManager.getInstance();
networkManager.addErrorListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
NetworkEvent n = (NetworkEvent) evt;
n.getError().printStackTrace();
success = false;
}
});
ConnectionRequest request = new ConnectionRequest()
{
{
setTimeout(40000);
}
#Override
protected void readResponse(InputStream input) throws IOException
{
InputStreamReader inputStreamReader = new InputStreamReader(input, "UTF-8");
int chr;
buffer = new StringBuilder();
//reading the answer
while ((chr = inputStreamReader.read()) != -1)
{
System.out.println("Append the character " + (char) chr);
buffer.append((char) chr);
}
response = buffer.toString();
response = response.trim();
data = new byte[buffer.length()];
int tmpCounter = buffer.length();
counter = 0;
while (counter != buffer.length())
{
for (int i = 0; i < tmpCounter; i++)
{
data[counter + i] = (byte) buffer.charAt(i);
}
counter += tmpCounter;
}
process(data);
dataEvent.setDataAvailable();
}
#Override
protected void handleException(Exception err)
{
success = false;
dataEvent.setDataAvailable();
}
};
request.setUrl(url);
request.setPost(false);
networkManager.addToQueue(request);
}
catch (Exception x)
{
x.printStackTrace();
}
Turns out the actual response didn't respond using UTF-8 the characters were just readable in my browser. I fixed it by specifying the response characters should be UTF-8

C# Can't read some characters from a file

New to c# here, I have done some research about this problem but couldn't find anything, lack of vocabulary maybe.
My task here is to a read a huge file and to extract only the lines which are following the conditions.
Code I'm using to test some things:
using (StreamReader sr = new StreamReader("SPDS_Test.doc"))
{
while ((line = sr.ReadLine()) != null)
{
try
{
if (line.Contains("R ") | line.Contains("E "))
{
data = line;
data = data.Remove(0, 1);
data= data.Replace(" ", "").Replace("N", "").Replace("+", ",").Replace("·", ",").Replace("?", ",").Replace("(", "").Replace(")", "");
Data.Add(data);
}
}
catch (Exception e)
{
Console.WriteLine("--------", e);
Console.WriteLine("--------Press any to continue---------");
Console.ReadKey();
}
}
foreach (string d in Data)
{
Console.WriteLine(d);
Console.ReadKey();
}
}
This is a part of the file :
R XRPA168VC
B A
L 手动紧急停堆
E XRPA300KS
A 反应堆停堆 汽轮机停机
R XRPR111VR
B IP
E F2/3(XRPR144KS, XRPR145KS, XRPR146KS)
What I noticed is that the letters aren't even letter if there chinese around it, for example I tried the condition line.Substring(0,1) == "R", it couldn't find those lines.
No matter what I do, my codes would only return this
XPR111VR
F2/3XRPR144KS, XRPR145KS, XRPR146KS
I really need to be able to extract every R and E lines.
I just tried to copy my whole doc into Notepad and put the encoding into UTF8,
seems to work afterward but not sure if it's reliable.
Try this...it works
using (StreamReader sr = new StreamReader("SPDS_Test.doc"))
{
string line;
string data;
List<string> Data = new List<string>();
while ((line = sr.ReadLine()) != null)
{
var utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(line);
string myString = utf8.GetString(utfBytes, 0,
utfBytes.Length);
try
{
if (myString.Contains("R ") || myString.Contains("E "))
{
data = line;
data = data.Remove(0, 1);
data= data.Replace(" ", "").Replace("N",
"").Replace("+", ",").Replace("·", ",").Replace("?",
",").Replace("(", "").Replace(")", "");
Data.Add(data);
}
}
catch (Exception e)
{
Console.WriteLine("--------", e);
Console.WriteLine("--------Press any to continue---------");
Console.ReadKey();
}
}
foreach (string d in Data)
{
Console.WriteLine(d);
Console.ReadKey();
}
}

Get IMSI from the SIM using codename1

I need to get the IMSI (International
Mobile Subsriber Identity) stored in the SIM card using codename1. Also in the case of dual or tri SIM phones, i need to get the IMSI for each SIM. Please, How do i get it?
Display.getMsisdn() will work for some devices but most don't allow accessing that information. For more information you can just use a native interface if you can access it that way.
Another way to get IMSI for dual Sim device:
Try this .. its working for me. Idea is to call service for iphonesubinfo function#3. you will get output as parcel value thats why I use getNumberFromParcel to extract number.
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by Apipas on 6/4/15.
*/
public class SimUtil {
public static String getIMSI_1() {
String imsiParcel = runCommand("service call iphonesubinfo 3");
String imsi = getNumberFromParcel(imsiParcel);
Log.d("apipas", "IMSI_1:" + imsi);
return imsi;
}
public static String getIMSI_2() {
String imsiParcel = runCommand("service call iphonesubinfo2 3");
String imsi = getNumberFromParcel(imsiParcel);
Log.d("apipas", "IMSI_2:" + imsi);
return imsi;
}
public static String runCommand(String src) {
try {
Process process = Runtime.getRuntime().exec(src);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[2048];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
// Waits for the command to finish.
process.waitFor();
return output.toString();
} catch (IOException e) {
Log.e("apipas", "IOException:" + e.getMessage());
return null;
} catch (InterruptedException e) {
Log.e("apipas", "InterruptedException:" + e.getMessage());
return null;
}
}
public static String getNumberFromParcel(String str) {
String res = "";
if (str != null && str.length() > 0) {
String lines[] = str.split("\n");
for (String line : lines) {
if (line == null || line.length() == 0)
continue;
String content[] = line.split("'");
if (content.length > 1) {
res += content[1].replace(".", "");
}
}
} else return "NA";
return res;
}
}
Then call these static methods like:
String imsi1 = SimUtil.getIMSI_1();
String imsi2 = SimUtil.getIMSI_2();
You'd need to set this permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

How to accelerate loading resource file in J2ME

I'm writing a J2ME application using J2ME Wireless Toolkit 2.2
I have the following code:
public class BusReader
{
private String[] fileNames;
private final String allFilesInfoFile = "files_in_dir";
public BusReader ()
{
fileNames = getFileNames ();
String busNo = getBusNo ("BusNo1p.bin");
}
public String[] getAllBusFiles ()
{
return fileNames;
}
public String getBusNo (String fileName)
{
String[] fileLines = loadResourceFile (fileName);
int linesCount = fileLines.length;
for (int i=0;i<linesCount;++i)
if (fileLines[i].equals ("[BusNo]") && i < linesCount-1)
return fileLines[i+1];
return null;
}
public String getDefaultDirection (String fileName)
{
String[] fileLines = loadResourceFile (fileName);
int linesCount = fileLines.length;
for (int i=0;i<linesCount;++i)
if (fileLines[i].equals ("[BusDirection]") && i < linesCount-1)
return fileLines[i+1];
return null;
}
private String[] getFileNames ()
{
return loadResourceFile (allFilesInfoFile);
}
private String[] loadResourceFile (String fileName)
{
String content = "";
try
{
Reader in = new InputStreamReader(this.getClass().getResourceAsStream(fileName), "iso-8859-2");
StringBuffer temp = new StringBuffer(1024);
char[] buffer = new char[1024];
int read;
while ((read=in.read(buffer, 0, buffer.length)) != -1)
temp.append(buffer, 0, read);
content = temp.toString();
} catch (IOException e) {
return null;
}
int len = content.length ();
if (content.charAt (len-1) == '\n' && content.charAt (len-2) == '\r')
{
String newContent = "";
for (int i=0;i<len-2;++i)
newContent += content.charAt (i);
content = newContent;
}
String[] fileLines = TString.Split ("\r\n", new TString(content));
for (int i=0;i<fileLines.length; ++i)
{
fileLines[i] = fileLines[i].trim ();
if (fileLines[i].length () == 0)
fileLines[i] = "";
}
return fileLines;
}
}
All works correctly, but the problem is when I'm trying to copy my application into mobile phone. On my mobile phone when I open the application before application show I must wait 35 seconds. This is because, constructor executes the function twice:
loadResourceFile (String fileName)
which loads the resource file. Files size which function is loading are: 1.22KB and 29KB.
The question is: How to accelerate loading function (loadResourceFile)?
I tried to create java class files as resource data but it exceeded java memory limit. I changed arrays String[][][][] to String[][][] and it was loading on my mobile phone in 15 seconds. I thought when I will load data as a resource it will work faster. My mobile phone: Nokia 3110c
I found it.
It was following lines (it takes 35 seconds):
if (content.charAt (len-1) == '\n' && content.charAt (len-2) == '\r')
{
String newContent = "";
for (int i=0;i<len-2;++i)
newContent += content.charAt (i);
content = newContent;
}

Need help fixing a try, catch error

I am trying to write a method that prints information into an array. the directions are: Create a second method for WordPath:
makeWordArray that takes a String file name as input, and it returns either an array or an ArrayList that stores WordData objects.
First, the method should open the file with new FileReader(file), call the numLines method to get the number of lines in file, and then create an array or an ArrayList of that size.
Next, close the FileReader and reopen the file. This time use BufferedReader br = new BufferedReader(new FileReader(file)). Create a loop to run through the file calling br.readLine(). For each line that you read in from br.readLine(), call the parseWordData on that String to get a WordData and store the WordData object into the appropriate index of the array or ArrayList.
My code is:
public class WordPath {
public static int numLines(Reader reader) {
BufferedReader br = new BufferedReader(reader);
int lines = 0;
try {
while(br.readLine() != null) {
lines = lines + 1;
}
br.close();
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
return lines;
}
public WordData[] makeWordArray(String file) {
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
WordData[] newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
}
I am running int a problem where the variable newArray can not be found, I believe because it is in the try statement. Is there any way to reformat this to work?
Like this:
public WordData[] makeWordArray(String file) {
WordData[] newArray = null;
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
You need to pull the declaration of the variable outside, but leave the assignment to that variable on the inside of the try.

Resources