Count items, rows, users, etc in Katalon Studio - selenium

I am having some problem with Katalon Studio.
Can I somehow count items on the page by class or something?
I can do it with JavaScript but I don't know how to do it with
groovy language in Katalon studio.
document.getElementsByClassName("").length
I'm trying to convert this JavaScript code into groovy but nothing happens.

You can also use WebUiBuiltInKeywords to findWebElements as specified in the following URL. It will return a list of elements matching the locator.
static List<WebElement> findWebElements(TestObject to, int timeOut)
// Internal method to find web elements by test object
Examples
def elements = WebUiBuiltInKeywords.findWebElements(to, 5)
println elements.size()

I think you can use the same method of size() like done in Table:
See documentation.
import org.openqa.selenium.By as By
import org.openqa.selenium.WebDriver as WebDriver
import org.openqa.selenium.WebElement as WebElement
WebDriver driver = DriverFactory.getWebDriver()
'To locate table'
WebElement Table = driver.findElement(By.xpath("//table/tbody"))
'To locate rows of table it will Capture all the rows available in the table'
List<WebElement> rows_table = Table.findElements(By.tagName('tr'))
'To calculate no of rows In table'
int rows_count = rows_table.size()
println('No. of rows: ' + rows_count)
Hope this helps you!

Do this
WebDriver driver = DriverFactory.getWebDriver()
def eleCount = driver.findElements(By.className("your-class")).size()
println eleCount //prints out the number of the elements with "your-class" class

Related

Selenium, groovy, can't perform any click(), sendKeys() or similar functions

I am not sure what I'm missing from my code. But I am trying to run a basic Groovy script, where I'm finding an element from the page, and clicking on it.
My code works, to the point where I add .click() or .sendKeys().
A few things to note are I'm running selenium on ReadyAPI. I have followed all the instructions from their help page to make sure I have the right drivers in the right folders.
My code is as follows:
import java.util.ArrayList;
import org.openqa.selenium.*
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement
import org.openqa.selenium.chrome.ChromeDriver
def PATH_TO_CHROMEDRIVER = context.expand( '${PATH_TO_CHROMEDRIVER}' );
System.setProperty("webdriver.chrome.driver", PATH_TO_CHROMEDRIVER);
def WebDriver driver = new ChromeDriver();
driver.get("https://www.rakuten.com/");
WebElement loginButtonId = driver.findElementsByXPath("//*[#name='email_address']");
loginButtonId.click();
driver.close();
return
The error msg I get is the following:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '[]' with class 'java.util.ArrayList' to class 'org.openqa.selenium.WebElement' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: org.openqa.selenium.WebElement() error at line: 12
I appreciate it if anyone could help here.
Thanks,
Your mistake is in this line:
WebElement loginButtonId = driver.findElementsByXPath("//*[#name='email_address']");
findElements you should use when you need to detect a list of elements,
If you want to get a single element use findElement:
WebElement loginButtonId = driver.findElementByXPath("//*[#name='email_address']");

How to select value from the auto suggestion text box?

From text boxI have tried many methods to find out the solution but I failed, So please help me regarding this Query
Website:- https://www.goibibo.com/
Inside that website when I am trying to select the value from 'FROM' auto-suggestion text box I failed to select because I am unable to inspect the dropdown, as it was dynamic and it was using some javascript functionality I guess. So please help me with this
You can use below code and instead of sending value hardcoded you can read it through Excel for dynamic.
import java.awt.AWTException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Testing {
public static WebDriver driver;
#Test
public void test() throws InterruptedException, AWTException {
System.setProperty("webdriver.chrome.driver", "./Driver/chromedriver");
driver = new ChromeDriver();
driver.get("https://www.goibibo.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
WebElement fromDropDwon = driver.findElement(By.xpath("//input[#id='gosuggest_inputSrc']"));
fromDropDwon.click();
fromDropDwon.sendKeys("Delhi (DEL)");
fromDropDwon.sendKeys(Keys.ARROW_DOWN);
fromDropDwon.sendKeys(Keys.ENTER);
}
}
Kindly upvote and it matches your expectation.
As it is auto suggesting the content and you want to select the first option from that drop down, you can use selenium's Keys enum and you can perform the selection like below :
driver.get("https://www.goibibo.com/");
WebElement from = driver.findElement(By.id("gosuggest_inputSrc"));
from.sendKeys("Bangalore");
Thread.sleep(3000);
from.sendKeys(Keys.ARROW_DOWN +""+ Keys.ENTER);
If you want to select other option than the first one then you can use the below xpaths to identify that drop down options :
//input[#id='gosuggest_inputSrc']/preceding-sibling::i/following::ul[contains(#id, 'react-autosuggest')]//li
Or
//ul[contains(#id, 'react-autosuggest')]//li
Below is the code to print all the options from that drop down and to select the particular value :
driver.get("https://www.goibibo.com/");
WebElement from = driver.findElement(By.id("gosuggest_inputSrc"));
from.sendKeys("Bangalore");
// Giving some delay so that the auto suggestion drop down will appear
Thread.sleep(3000);
// Fetching options from dropdown
List<WebElement> dropdownOptions = driver.findElements(By.xpath("//ul[contains(#id, 'react-autosuggest')]//li"));
// Printing all the option text
for(WebElement element : dropdownOptions) {
System.out.println(element.getText());
}
// Selecting the first option
dropdownOptions.get(0).click();
I hope it helps...
Go to sources tab > Click on the text box > Press F8 or (FN + F8) when disappearing element is available on webpage( By doing this webpage will be switch to debug mode and element can be inspected now).
If you need XPath for first autosuggest option, try
//ul[#id='react-autosuggest-1']/li[#id='react-autosuggest-1-suggestion--0']
You can replace 0 with1 to get second option, 2 - for third option, etc

Finding a string in an URL's source code with selenium webdriver

I'm trying to extract a keyword/string from a website's source code using this python 2.7 script:
from selenium import webdriver
keyword = ['googleadservices']
driver = webdriver.Chrome(executable_path=r'C:\Users\Jacob\PycharmProjects\Testing\chromedriver_win32\chromedriver.exe')
driver.get('https://www.vacatures.nl/')
elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")
for searchstring in keyword:
if searchstring.lower() in str(source_code).lower():
print (searchstring, 'found')
else:
print (searchstring, 'not found')
The browser fortunately opens when the script is running, but I'm not able to extract the desired keywords from it's source code. Any help?
As others have said, the issue isn't your code but simply that googleadservice isn't present in the source code.
What I want to add, is that your code is a bit over engineered, since all you seem to do is either return true or false if a certain string is present in the source code.
You can achieve that much easier with a better xpath like //script[contains(text(),'googletagmanager')] and than use find_element_by_xpath and catch the possible NoSuchElementException. That might save you time and you don't need the for loop.
There are other possiblities as well, using ExpectedConditions or find_elements_by_xpath and then check if the returned list is greater than 0.
I observed that googleadservices is NOT present in the web page source code.
There is NO issue with the code.
I tried with GoogleAnalyticsObject, and it is found.
from selenium import webdriver
keyword = ['googleadservices', 'GoogleAnalyticsObject']
driver = webdriver.Chrome()
driver.get('https://www.vacatures.nl/')
elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")
for searchstring in keyword:
if searchstring.lower() in str(source_code).lower():
print (searchstring, 'found')
else:
print (searchstring, 'not found')
Instead of using //* to find the source code
elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")
Use the following code:
source_code = driver.page_source

Selenium webdriver get all the data attributes of an element

Using Selenium webdriver I have the following element
<div data-1223="some data" data-209329="some data" data-dog="some value">
Is there a way to get all the data- attributes of the element?
For a specific attribute I can use
elem.getAttribute('data-1223')
but how can I get all the data attributes together
Use below Code:-
WebElement element = "Your Element"; // Your element
JavascriptExecutor executor = (JavascriptExecutor) driver;
Object aa=executor.executeScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;", element);
System.out.println(aa.toString());
Hope it will help you :)
No. There is no way in Selenium WebDriver to access any attribute whose full name you don't know. You can't even enumerate over all attributes of a WebElement.
It doesn't look like the jsonwire protocol supports this concept. The GET_ELEMENT_ATTRIBUTE command takes a list of attribute names, not a list of attribute name patterns.
It is probable that you could query via a JavascriptExecutor and either XPath or CSS query to find all the attribute names for your element, then use that to loop over getAttribute. But if you're going to do that, you can just construct your XPath or CSS query to give you the values directly, and leave the WebElement out of it completely.
This concept works very well. Try this!
WebElement element = driver.findElement(By.tagName("button"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
Object elementAttributes = executor.executeScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;",element);
System.out.println(elementAttributes.toString());

selenium span link li not working

I am new to selenium. I am practicing to write a test case on http://www.countdown.tfl.gov.uk. Below are the steps I followed:
a) I opened the browser to selenium Web Driver
b) Found the search text Box and enter H32 and clicked on search button to selenium.
Till this part it works fine.
Now on the page I am actually getting two records on the left side of the page under the search. I am actually trying to click on the first one i.e. "Towards Southall,Townhall" link. Nothing is happening.
Below is my code:
public class CountdownTest {
#Test
public void tflpageOpen(){
WebDriver driver = openWebDriver();
searchforBus(driver,"H32");
selectrouteDirection(driver)
}
//open the countdowntfl page
private WebDriver openWebDriver(){
WebDriver driver = WebDriverFactory.getWebDriver("FireFox");
driver.get("http://www.countdown.tfl.gov.uk");
return driver;
}
private void searchforBus(WebDriver driver,String search){
WebElement searchBox = driver.findElement(By.xpath("//input[#id='initialSearchField']"));
searchBox.sendKeys(search);
WebElement searchButton = driver.findElement(By.xpath("//button[#id='ext-gen35']"));
searchButton.click();
}
private void selectrouteDirection(WebDriver driver){
WebElement towardssouthallLink= driver.findElement(By.xpath("//span[#id='ext-gen165']']"));
((WebElement) towardssouthallLink).click();
}
}
Please help me.
Thanks.
Since you are getting NoSuchElement Exception now, you may try the following code with the usage of WebDriver explicit wait.
WebDriverWait wait = new WebDriverWait(driver, 15);
WebElement towardssouthallLink = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("(//*[#id='route-search']//li/span)[1]")));
towardssouthallLink.click();
Or WebDriver implicit wait
WebDriver driver = WebDriverFactory.getWebDriver("FireFox");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://www.countdown.tfl.gov.uk");
Tips:
The search results need some time to be retrieved, so please use Explicit wait or Implicit wait.
Don't use locators like span[#id='ext-gen165'], they are ExtJs auto generated.
In this case, css selector can also be used: #route-search li:nth-of-type(1) > span
You aren't calling selectrouteDirection.
You probably want:
#Test
public void tflpageOpen(){
WebDriver driver = openWebDriver();
searchforBus(driver,"H32");
selectrouteDirection(driver);
}
You also don't need to cast here:
((WebElement) towardssouthallLink).click();
It's already a WebElement anyway.
I found that id for those links are dynamically generated. ids are of the form 'ext-genXXX' where XXX is number which is dynamically generated hence varies each time.
Actually, you should try with linkText:
For 'Towards Southall, Town Hall'
driver.findElement(By.linkText("Towards Southall, Town Hall")).click
For 'Towards Hounslow, Bus Station'
driver.findElement(By.linkText("Towards Hounslow, Bus Station")).click
Here is a logic:
Get all elements which have id starts with 'ext-gen' & iterate over it & click on link with matching text. Following is Ruby code(sorry, I don't know Java well):
links = driver.find_elements(:xpath, "//span[starts-with(#id, 'ext-gen')]")
links.each do |link|
if link.text == "Towards Southall, Town Hall"
link.click
break
end
end