unable to get theaders - java

im currently having a problem in getting the headers title of a table to make a validation, it work great until column 6, because when it goes to next one which isn't visible the .getText() is blank. I no the xpath is correct.
public void getAndSaveDataOfTable (final String tabla) throws FileNotFoundException{
WebElement element = driver.findElement(By.xpath(tabla));
List<WebElement> elements = element.findElements(By.xpath("th"));
Assert.assertTrue(elements.size() > 1);
int cantelements = elements.size();
for (int i = 1; i <= cantelements; i++) {
String data = driver.findElement(
By.xpath(".//div[#class='ui-datatable-scrollable-header-box']//table/thead/tr/th["+ i + "]/span[1]")).getText();
System.out.println("EL nombre del encabezado " + i + " " + data);
datosFila.put(i, data);
}
So between column 7and 20 I can't get the text of the header.

If you are going to be using the JavascriptExecutor several times (you said your issue is on multiple columns 7-20) I would suggest you can optimize by running JS only once and then iterating through in Java, rather than running JS again for every operation. The JavascriptExecutor is slow, and you'll save whole seconds on the total test time by avoiding even 12+ extra JS executions.
// JavaScript to get text from tHeads
String getTheadTexts =
"var tHeads = []; " +
"for (i = o; i < 20; i++) { " +
"var cssSelector = 'div.ui-datatable-scrollable-header-box table thead tr th' + i + ' span:nth-of-type(1)'; " +
"var elem = document.querySelector(cssSelector); " +
"var elemText = ''; " +
"if ((elem.textContent) && (typeof (elem.textContent) != 'undefined')) { " +
"tHeads.push(elem.textContent); " +
"} else { " +
"tHeads.push(elem.innerText); " +
"} " +
"} " +
"return tHeads; ";
// Execute the JS to populate a List
List<String> tHeadTexts = (ArrayList<String>) js.executeScript(getTheadTexts);
// Do some operation on each List item
int i = 0;
for (String data: tHeadTexts){
System.out.println("EL nombre del encabezado " + i + " " + data);
datosFila.put(i, data);
i++;
}

I ran into what sounds like what you're running into. Take a look at my post on
WebElement getText() is an empty string in Firefox if element is not physically visible on the screen
I ended up solving it by using a little bit of JavaScript to columns "into view". Hopefully this helps you out.
private void scrollToElement(WebElement element){
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
}

Related

How to select multiple checkboxes in selenium(java)?

I am trying to select all checkboxes whose value is matched to my value.
Code is working fine when the web page has no vertical scroll. But if web page has some more data then the checkbox is not selected as I want.
Here is my code-
List<WebElement> rselect = tagdis1.findElements(By.className("row-selection-checkbox"));
System.out.println("Row selection Size- " + rselect.size());
List<WebElement> record = driver.findElements(By.id("$ctrl.item.id"));
System.out.println("Size- " + record.size());
int DocNameCount = 0;
for (int j = 0; j < record.size(); j++) {
String Pname = record.get(j).getText();
System.out.println("Pdf name- " + Pname);
if (Pname.equals(docName + ".pdf")) {
// here total 4 records i get but able to click only on 3 records
System.out.println(j + " " + Pname);
rselect.get(j).click();
Thread.sleep(2000);
}
}
Please use scroll option in your operation,
/*
* By
* scroll to the element and wait
*/
public void scroll(By element){
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);",driver.findElement(element));
log.info("Scrolling down");
}

How to prevent getting duplicate hrefs using getAttribute Selenium

I keep getting same links from the site which I'm testing.
This is my code
"
List<WebElement> activeLinks = new ArrayList<WebElement>();
//2.Iterate LinksList: Exclude all the links/images - doesn't have any href attribute and exclude images starting with javascript.
boolean breakIt = true;
for(WebElement link:AllTheLinkList)
{
breakIt = true;
try
{
//System.out.println((link.getAttribute("href")));
if(link.getAttribute("href") != null && !link.getAttribute("href").contains("javascript") && link.getAttribute("href").contains("pharmacy")) //&& !link.getAttribute("href").contains("pharmacy/main#"))
{
activeLinks.add(link);
}
}
catch(org.openqa.selenium.StaleElementReferenceException ex)
{
breakIt = false;
}
if (breakIt)
{
continue;
}
}
//Get total amount of Other links
log.info("Other Links ---> " + (AllTheLinkList.size()-activeLinks.size()));
//Get total amount of links in the page
log.info("Size of active links and images in pharmacy ---> "+ activeLinks.size());
for(int j=0; j<activeLinks.size(); j++) {
HttpURLConnection connection = (HttpURLConnection) new URL(activeLinks.get(j).getAttribute("href")).openConnection();
connection.setConnectTimeout(4000);
connection.connect();
String response = connection.getResponseMessage(); //Ok
int code = connection.getResponseCode();
connection.disconnect();
//System.out.println((j+1) +"/" + activeLinks.size() + " " + activeLinks.get(j).getAttribute("href") + "---> status:" + response + " ----> code:" + code);
log.info((j+1) +"/" + activeLinks.size() + " " + activeLinks.get(j).getAttribute("href") + "---> status:" + response + " ----> code:" + code);
}
And this is my output:
I'm getting same links again and again. it's like they are repeating.
Anybody can help me with this?
Try copying the list items to a set because set does not allow duplicates.
For example:
WebDriver driver = new ChromeDriver();
List<WebElement> anchors = driver.findElements(By.tagName("a"));
Set<WebElement> hrefs = new HashSet<WebElement>(anchors);
Iterator<WebElement> i = hrefs.iterator();
while(i.hasNext()) {
WebElement anchor = i.next();
if(anchor.getAttribute("href").contains(href)) {
anchor.click();
break;
}
}
Hope this helps.

How do I properly print enumerator elements?

I am trying to understand java program written by someone else and I do not know java. I have written a short method fro dumping attributes of request object.
public void dumpRequest(HttpServletRequest request) {
String[] attrNames = new String[100]; // hard coded
int ani = 0;
Enumeration rns = request.getAttributeNames();
while (rns.hasMoreElements()) {
out.println("attribute name: " + rns.nextElement());
attrNames[ani] = rns.nextElement().toString();
ani = ani + 1;
}
out.println("" + ani + " atributes");
String cn;
for (int n = 0; n < ani; n++) {
cn = attrNames[n];
out.println("** " + cn + " - " + request.getAttribute(cn));
}
out.println("++++++++++++++++++++++");
}
To my horror, I have realised that NetBeans variables tab shows twice more attributes on the request object compared to my code output.
The enumeration seems to be documented here:
https://tomcat.apache.org/tomcat-4.1-doc/catalina/docs/api/org/apache/catalina/util/Enumerator.html
What am I doing wrong?
You call nextElement method twice in this block:
while (rns.hasMoreElements()) {
out.println("attribute name: " + rns.nextElement());
attrNames[ani] = rns.nextElement().toString();
ani = ani + 1;
}
you should call nextElement once. Put it in variable and then use that variable.

After selecting the second option from dropdown, the WebElement is still showing the record of first option

There is a dropdown list where each selection has a different URL under the dropdown buttons. Suppose when I select first option then it shows 10 hyperlink and select the second option it shows 5 hyperlinks, etc.
Problem - When I select the second option, it is still showing 10 hyperlinks instead of 5 and shows
org.openqa.selenium.StaleElementReferenceException: Element not found
in the cache - perhaps the page has changed since it was looked up
Select select = new Select(selectdropdown);
List<WebElement> options = select.getOptions();
int isize = options.size();
for (int i = 0; i < isize; i++)
{
String value = select.getOptions().get(i).getText();
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
WebElement WebElementer = driver.findElement(By.xpath("//*[#id='content-inner']"));
List<WebElement> elementList = new ArrayList<>();
elementList = WebElementer.findElements(By.cssSelector("a[href]"));
System.out.println("Total number of links found" + elementList.size());
System.out.println("to check wheather link is working or not");
for (WebElement element : elementList)
{
try
{
System.out.println("URL: " + element.getAttribute("href").trim() + " returned "
+ islinkBroken(new URL(element.getAttribute("href").trim())));
}
catch (Exception exp)
{
System.out.println("At " + element.getAttribute("innerHTML")
+ " Exception occured -> " + exp.getMessage());
}
}
}
where you selecting the element ?? (C# syntax example)
IList<IWebElement> accountsDDL = driver.FindElements(By.XPath("//select[#id='yourSelectId']/option"));
for (int i = 1; i < accountsDDL.Count; i++)
{
new SelectElement(driver.FindElement(By.Name("yourSelectId"))).SelectByText(accountsDDL[i].Text); // Selecting the element
}
In java
I spent a little time cleaning up your code and added a few things. See if this works. As Leon said, I think one of the issues was that you didn't have code that actually changed the selected option.
Select select = new Select(selectdropdown);
for (int i = 0; i < select.getOptions().size(); i++)
{
select.selectByIndex(i); // you were missing this line?
// String value = select.getFirstSelectedOption().getText(); // this variable is never used
// driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS); // this doesn't do what you think it does
// I think this next line should work. I combined the two locators into one.
List<WebElement> elementList = driver.findElements(By.cssSelector("#content-inner a[href]"));
System.out.println("Total number of links found" + elementList.size());
System.out.println("to check wheather link is working or not");
for (WebElement element : elementList)
{
try
{
String href = element.getAttribute("href").trim();
System.out.println("URL: " + href + " returned " + islinkBroken(new URL(href)));
}
catch (Exception exp)
{
System.out.println("At " + element.getAttribute("innerHTML") + " Exception occured -> " + exp.getMessage());
}
}
}
Suggestion: It might be useful to you to add the selected option text to your exception message.

How to get list of tabs from Salesforce Org using Java?

Is there a way to get the list of tabs from a Salesforce Org? I have tried using Metadata wsdl file and created a jar using force-wsc.jar. But I'm not able to retrieve the list of tabs. Please help or provide some pointers. Thanks in advance.
For getting information about Salesforce tabs you can use SOAP API method describeTabs(). Here is an example of using for Java:
public void describeTabsSample() {
try {
// Describe tabs
DescribeTabSetResult[] dtsrs = connection.describeTabs();
System.out.println("There are " + dtsrs.length +
" tab sets defined.");
// For each tab set describe result, get some properties
for (int i = 0; i < dtsrs.length; i++) {
System.out.println("Tab Set " + (i + 1) + ":");
DescribeTabSetResult dtsr = dtsrs[i];
System.out.println("Label: " + dtsr.getLabel());
System.out.println("\tLogo URL: " + dtsr.getLogoUrl());
System.out.println("\tTab selected: " +
dtsr.isSelected());
// Describe the tabs for the tab set
DescribeTab[] tabs = dtsr.getTabs();
System.out.println("\tTabs defined: " + tabs.length);
// Iterate through the returned tabs
for (int j = 0; j < tabs.length; j++) {
DescribeTab tab = tabs[j];
System.out.println("\tTab " + (j + 1) + ":");
System.out.println("\t\tName: " +
tab.getSobjectName());
System.out.println("\t\tLabel: " + tab.getLabel());
System.out.println("\t\tURL: " + tab.getUrl());
DescribeColor[] tabColors = tab.getColors();
// Iterate through tab colors as needed
DescribeIcon[] tabIcons = tab.getIcons();
// Iterate through tab icons as needed
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}

Categories

Resources