Scenario
I want to collect all the selected [checkbox - checked] records in a table. Below is my method,
def getAlltheSelectedRecordId(String tableName){
WebDriver driver = DriverFactory.getWebDriver()
WebElement RefTable = driver.findElement(By.xpath("//*[#id='${tableName}']/tbody"))
List<WebElement> RowsOf_RefTable = RefTable.findElements(By.tagName('tr'))
int Totalcount = RowsOf_RefTable.size()
for (int row : (1..Totalcount)) {
boolean isChecked = driver.findElement(By.xpath("//*[#id='${tableName}']/tbody/tr[' + row + ']/td[2]/input")).isSelected()
println isChecked
boolean isChecked1 = driver.findElement(By.xpath("//*[#id='${tableName}']/tbody/tr[' + row + ']/td[2]/input")).selected
println isChecked1
if(isChecked){
String selectedRecordID = driver.findElement(By.xpath("//*[#id='${tableName}']/tbody/tr[' + row + ']/td[5]/a")).getText()
println selectedRecordID
}
}
}
Passing the table name as parameter and collect all the selected records in the table. But unfortunately always isChecked and isChecked1 return false
Please guide me where is the problem
The problem lies in the way, the strings are put together and the problem is already visible with the syntax highlighting here in SO:
By.xpath("//*[#id='${tableName}']/tbody/tr[' + row + ']/td[2]/input")
"...' + row + '..." does not put the value of row inside the string -- only this exact "code".
The solution is to use the proper quotes to end the string:
By.xpath("//*[#id='${tableName}']/tbody/tr[" + row + "]/td[2]/input")
Or even better, stick to the scheme already started in the beginning of the string: use Groovys string replacment:
By.xpath("//*[#id='${tableName}']/tbody/tr[${row}]/td[2]/input")
Related
I have a JList in which I am formatting the text before it is added to the JList cell using HTML. I'm doing this because I'm lazy and don't want to get complex with a cellRenderer. I only need 2 separate lines in each JList cell so HTML just seemed quicker and easier for such a simple requirement, however when I run this it correctly formats it, however, the text does not start on the edge of the button. I'm assuming this is because the HTML takes up space in whitespaces in which case I assume I can't fix that?
public static void receiveDataEmailList(String data) {
Scanner scLine = new Scanner(data).useDelimiter("&");
int num = scLine.nextInt();
String[] emails = new String[num];
for (int i = 0; i < num; i++) {
emails[i] = "" + "<html><ul style=\"list-style-type:none;\"><li style=\"font-size:10px\">" + scLine.next() + "</li><li style=\"font-size:8px\">" + "Subject: " + "Hello" + "</li></ul></html>";
}
EmailList.setListOfEmails(emails);
}
I'm using Selenium to loop through an ArrayList of Strings in order to use each string in an xPath expression in order to select its appropriate checkbox on a website.
The problem is, when I use the for loop, the variable containing the string doesn't seem to create a valid xPath, yet when I simply substitute the string in myself it works fine.
For example, here is my ArrayList declaration with some values added.
ArrayList<String> fieldList = new ArrayList<String>();
fieldList.add("Street");
fieldList.add("City");
fieldList.add("Country");
If I then use the following code, it goes into the catch block
WebDriverWait waitForElement = new WebDriverWait(driver, 1);
for (String cField: fieldList) {
try {
waitForElement.until(ExpectedConditions.elementToBeClickable(By.xpath("//td[following-sibling::td[2] = " + cField + "]/input")));
WebElement checkBox = driver.findElement(By.xpath("//td[following-sibling::td[2] = " + cField + "]/input"));
checkBox.click();
} catch (Exception error) {
System.out.println("Couldn't find " + cField);
}
}
Telling me it couldn't find "Street" for example.
Yet when my try block contains the following, with the value explicitly stated, it works:
waitForElement.until(ExpectedConditions.elementToBeClickable(By.xpath("//td[following-sibling::td[2] = 'Street']/input")));
WebElement checkBox = driver.findElement(By.xpath("//td[following-sibling::td[2] = 'Street']/input"));
What am I doing wrong? Thanks a lot.
You are forgetting to quote your strings in the XPath expression. Add single quotes around cField:
waitForElement.until(ExpectedConditions.elementToBeClickable(
By.xpath("//td[following-sibling::td[2] = '" + cField + "']/input")));
// quotes added here ---^ and here ---^
WebElement checkBox =
driver.findElement(By.xpath("//td[following-sibling::td[2] = '" + cField + "']/input"));
// quotes added here ---^ and here ---^
Here's the table (tblemployees)
How can I convert my code that used text files to a code that will use database (tables).
int intcurrentLine = -1;
String[] strLineSplit = (sb.toString()).split("\\r?\\n"); // converts sb to string then splits it by line
int intNumElements = strLineSplit.length; // number of elements
while (intcurrentLine != (intNumElements - 1)) {
intcurrentLine++;
String[] strWords = (strLineSplit[intcurrentLine]).split(" ", 2); // splits the current line by the first instance(space)
if (strEmpID.equals(strWords[0])) { // checks if the employee ID is available
JOptionPane.showMessageDialog(null, "Welcome " + strWords[1] + ", you have successfully logged in.");
strCheck = 1; // to confirm and go to time in and out process
break;
}
if ((intcurrentLine + 1) == intNumElements) { // condition to state that ID cant be found from the employee list
JOptionPane.showMessageDialog(null, "No such employee, please check the ID No. that you entered.");
}
}
Now I would like to search a column if it contains an Employee number. How do I put it to a condition, I've been searching but unable to find a clear answer. They only put how to search like this
String queryCheck = "SELECT * from messages WHERE EmpIDNo = 'COMSCI0001'";
ResultSet res = st.executeQuery(queryCheck);
then I'm lost, how to make a condition where if the employee no. doesn't exists something would happen else something would happen. I'm just confuse how to make a condition for that.
You can do like this:
String queryCheck = "SELECT * FROM messages WHERE EmpIDNo = 'COMSCI0001' LIMIT 1";
ResultSet res = st.executeQuery(queryCheck);
boolean exists = res.next();
The boolean variable exists will indicate whether a matching record exists or not.
Notice that I added LIMIT 1 at the end of the SQL as an optimization to avoid fetching more data than you really need.
I have extracted multiple data from an HTML using Jsoup and now I am trying to insert one by one into a derby db using JDBC on netbeans.
Here is my code:
public String nameOf() {
String nameStr = null;
String nameResults = "";
for(int j=100;j<=110;j++) {
refNum = j;
//System.out.println("Reference Number: " + refNum);
try {
//crawl and parse HTML from definition and causes page
Document docDandC = Jsoup.connect("http://www.abcd.edu/encylopedia/article/000" + refNum + ".htm").get();
// scrape name data
Elements name = docDandC.select("title");
nameStr = name.get(0).text();
//System.out.println(nameStr);
nameResults += nameStr + " ";
} catch (Exception e) {
//System.out.println("Reference number " + refNum + " does not exist.");
}
}
return nameResults;
So this method takes the names of diseases from 10 different HTMLs. What I am trying to do is to insert one name at a time to a derby db that I have created using JDBC. I have everything set up and all I have left to do is to insert each name in the corresponding name field of a table named DISEASE (which has fields: id, name, etc).
nameResults += nameStr + " ";
This part worries me as well since some diseases can have multiple words. Maybe I should use a list of some sort?
Please help! Thanks in advance.
Something like:
public List<String> nameOf() {
...
List<String> nameResults = new ArrayList<String>();
...
nameResults.add(nameStr);
...
return nameResults;
I need to insert data from my parsed XML file to mySQL table. Problem is that I have few attributes and don't know how to insert them in one row. I tried with updateString but it writes only last attribute.
Here is example from XML file:
<Tr rn=\"999999999999999\" vr=\"T\" sSpre=\"S\" reg=\"P\" dSpre=\"2010-09-30\" dOdprt=\"2000-01-01\" iban=\"SI56\" eno=\"R\" vir=\"R\" maticnaPps=\"00000000\"><Imetnik davcna=\"0000000\" matSub=\"0000000\" drz=\"705\"><PopolnoIme>xxx</PopolnoIme><KratkoIme>xxx</KratkoIme><Naslov sifTipNaslova=\"01\" sifObcina=\"039\" sifPosta=\"1303\" sifUlica=\"0000\" sifNaselje=\"059\" stHisna=\"027\" sifHsmid=\"11694551\"><Obcina>xxx</Obcina><Posta>xxx</Posta><Ulica>xxx</Ulica><Naselje>xxx</Naselje></Naslov></Imetnik></Tr>
This is scratch from my java program that I used for writing in mySQL table.
if (myWorkLine.substring(0,4).equals(Tr)) {
uprs.afterLast();
uprs.moveToInsertRow();
if (myWorkLine.contains(Tr)) {
myWorkLine = myWorkLine.substring(myWorkLine.indexOf(Tr)+4);
while (!myWorkLine.substring(0,1).equals("<")) {
myTag = myWorkLine.substring(0,myWorkLine.indexOf("="));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("=")+2);
myValue = myWorkLine.substring(0,myWorkLine.indexOf("\""));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("\"")+2);
uprs.updateString("Tr",myTag + " " + myValue);
if (myWorkLine.substring(0,myWorkLine.indexOf("\">")).indexOf(">") > 0)
break;
}
}
So once again, I need that in MySQL table column Tr contains attributes rn value, vr value, sSpre value,...
Thanks in advance.
P.S.: Please don't ask why I'm parsing XML file by this method, I had to do it that way. :)
Your code will repeatedly replace the "Tr" column with your concatenation of tag + " " + value so it'll only be the last one that goes in. Don't you perhaps want the different tags to go in different columns? Or maybe you need to continue concatenating and only call updateString at the end.
Could you post the desired table row for the given XML? That should help in determining what you are trying to achieve.
For example, if you just want to append them:
StringBuffer tr = new StringBuffer();
while (!myWorkLine.substring(0,1).equals("<")) {
myTag = myWorkLine.substring(0,myWorkLine.indexOf("="));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("=")+2);
myValue = myWorkLine.substring(0,myWorkLine.indexOf("\""));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("\"")+2);
tr.append(myTag + " " + myValue).append(",");
if (myWorkLine.substring(0,myWorkLine.indexOf("\">")).indexOf(">") > 0)
break;
}
if (tr.length() > 0) {
tr.deleteCharAt(tr.length()-1); // get rid of last comma
}
uprs.updateString("Tr",tr.toString());