Selenium Java can't always click the same place - java

I am trying to automate with Java. What I need to do is to choose a random product from the product list and then press the "add to favorite" button on the top left of that product. However, whenever I try to run this test, sometimes it adds the product to the favourite, and sometimes instead of pressing the favorite button, it presses on the product and the test results in an error.
The url I'm trying to pick a random product and add to favourite: https://www.turkcell.com.tr/pasaj/cep-telefonu
mycode:
//Add 3 random items
for (int i = 0; i < 3; i++) {
Random random = new Random();
int productOrder = driver.findElements(By.xpath("//*[contains(#class, 'm-grid-col-4 product')]")).size();
int randomNum = random.nextInt(productOrder)+1;
TimeUnit.SECONDS.sleep(2);
System.out.println(randomNum + "th product selected");
TimeUnit.SECONDS.sleep(2);
//int newRandom = randomNum+1;
TimeUnit.SECONDS.sleep(2);
WebElement randomFavoriteClick = driver.findElement(By.xpath("(//*[#class='m-grid-col-4 product'])["+randomNum+"]/a/div[1]/span"));
js.executeScript("arguments[0].scrollIntoView();", randomFavoriteClick);
TimeUnit.SECONDS.sleep(5);
randomFavoriteClick.click();
TimeUnit.SECONDS.sleep(3);
I tried changing the Xpaths but nothing changed.

To confirm exactly where I want to click, I added "actions" to the project and moved my cursor over the element before clicking with the MoveToElement function and it works for now.
Actions actions = new Actions(driver);
for (int i = 0; i < 3; i++) {
Random random = new Random();
int productOrder = driver.findElements(By.xpath("//*[contains(#class, 'm-grid-col-4 product')]")).size();
int randomNum = random.nextInt(productOrder)+1;
TimeUnit.SECONDS.sleep(2);
System.out.println(randomNum + "th product selected");
TimeUnit.SECONDS.sleep(2);
//int newRandom = randomNum+1;
TimeUnit.SECONDS.sleep(2);
WebElement randomFavoriteClick = driver.findElement(By.xpath("(//*[#class='m-grid-col-4 product'])["+randomNum+"]/a/div[1]/span"));
actions.moveToElement(randomFavoriteClick);
TimeUnit.SECONDS.sleep(2);
js.executeScript("arguments[0].scrollIntoView();", randomFavoriteClick);
TimeUnit.SECONDS.sleep(4);
randomFavoriteClick.click();
TimeUnit.SECONDS.sleep(4);
}

Related

Android + Appium: Scroll inside ListView to specific position and click on it

can someone please help me with this.
Task: Open ListView element in Android App, scroll to specific position and click on it. If element wasn't found, than scroll to the bottom of the list and stop to search and drop the test with exception.
//Yes, I have been looking for a solution on other questions, but I can't combine then to use in my case.
What did i get:
1) Test swipes inside ListView to specific position and clicks on it;
2) Test stacks in loop in the bottom of ListView.
Questions:
1) How to stop test with exception if specific position wasn't found when the bottom of ListView was reached?
2) Swipe looks like incorrect solution and seems there must be used another solution, or no?
code:
public void scrollToElementFromList (String keyword_locator){
// keyword_locator = (By.xpath("//*[#resource-id = 'android:id/text1'][#text = 'Spain']"))
boolean token = false;
while(!token) {
if (this.isElementPresent(keyword_locator)){
waitForElementAndClick(keyword_locator,"Cannot click selected element",3);
token = true;
} else {
TouchAction action = new TouchAction(driver);
WebElement element = driver.findElement(By.xpath("//android.widget.ListView"));
int middleX = element.getLocation().getX() + element.getSize().getWidth() / 2;
int upperY = element.getLocation().getY();
int lowerY = upperY + element.getSize().getHeight() - 50;
action.press(middleX, lowerY).waitAction(1200).moveTo(middleX, upperY).release().perform();
continue;
}
}
}
answer:
public void scrollToElementFromList (String locator, String keyword_locator, int max_swipes){
By by = this.getLocatorByString(locator);
boolean element_found = false;
int already_swiped = 0;
while(!element_found) {
if (this.isElementPresent(keyword_locator)){
waitForElementAndClick(keyword_locator,"Cannot click selected element",3);
element_found = true;
} else if (already_swiped > max_swipes){
throw new AssertionError("Cannot find element by swiping up.");
}
else {
TouchAction action = new TouchAction(driver);
WebElement element = driver.findElement(by);
int middleX = element.getLocation().getX() + element.getSize().getWidth() / 2;
int upperY = element.getLocation().getY();
int lowerY = upperY + element.getSize().getHeight() - 50;
action.press(middleX, lowerY).waitAction(1200).moveTo(middleX, upperY).release().perform();
++already_swiped;
continue;
}
}
}

How to multi select the items in table without using action class for IE browser

IE browser does not support Action class. Is it possible to multi select the items in a table using any other way? If any, please share.
Please find the sample structure of the table to select the values. Now i want to select the Text1, Text3 & Text5 values. Am able to select using Action class in Chrome, FF browser using selenium 2.52.0 but not able to select in IE/Safari.
<table>
<tr><td><div><span>Text1<span/><div/><td/><tr/>
<tr><td><div><span>Text2<span/><div/><td/><tr/>
<tr><td><div><span>Text3<span/><div/><td/><tr/>
<tr><td><div><span>Text4<span/><div/><td/><tr/>
<tr><td><div><span>Text5<span/><div/><td/><tr/>
<table>
Function used to click:
String[] items = itemName.split("\n");// Items to be clicked
Actions builder = new Actions(driver);
for(int counter = 0; counter < items.length; counter++)
{
this.listingRows = this.listing.findElement(By.cssSelector("table[id='mainTable']"));
List<WebElement> element = listingRows.findElements(By.cssSelector("tr[class='sample']>td>div>span")); //Getting the row elements
int itemCnt = element.size();
String item;
for(int i =0;i<itemCnt;i++){
item = element.get(i).getText();
if(item.equalsIgnoreCase(items[counter])){
builder.keyDown(Keys.CONTROL).click(element.get(i)).keyUp(Keys.CONTROL);
builder.build().perform();
}
}
}
First, you can inspect the table
WebElement data1=d.findElement(By.xpath(""));
then, select row by row
List<WebElement> tableRows = data1.findElements(By.tagName("tr"));
using loop you can repeat through out the columns
for (int i=0; i<rowSize; i++)
{
WebElement webRow = tableRows.get(i);
//Get all cell values in each row
List<WebElement> allCells = webRow.findElements(By.tagName("td"));
//System.out.println(allCells.size());
if(allCells.size() > 1)
{
row = st1.createRow(i);
for (int j=0; j<allCells.size(); j++)
{
WebElement webCell = allCells.get(j);
String text = webCell.getText();
if(text.length()>3)
{
cell = row.createCell(j);
cell.setCellValue(webCell.getText());
}
}
}
try once..!!

How to initialize another WebElement inside the method in Java with Selenium

I'm a bit concerned with the minor problem that I'm facing. I have a test case where I need to pick up any value from the drop down. After selection entire web page reloads and I have 2 options. If warning message appears, I need to click on drop down again and choose another value. If warning message doesn't appear, just click on "Continue" button. All my values inside the drop down have the same id which only differs in ending:
uxMiniFinderVoyageSelect_chzn_o_1
uxMiniFinderVoyageSelect_chzn_o_2
uxMiniFinderVoyageSelect_chzn_o_3
uxMiniFinderVoyageSelect_chzn_o_4
till 30. What I did I called Random class where I set up variable from 1 - 30
Random random = new Random();
int x = random.nextInt(30) + 1;
Now I look for my element this way
WebElement valueFromDropDown = driver.findElement(By.id("uxMiniFinderVoyageSelect_chzn_o_" + x));
But if warning message appears and I need to click on another value, my code picks up the same value over and over. The question is how to correctly and with less code writing click on another element in drop down? The full class looks like this
public class SomeClassName{
Random random = new Random();
int x = random.nextInt(30) + 1;
#FindBy(xpath = "someXpathExpression") private WebElement dropDown;
#FindBy(xpath = "someXpathExpression") private WebElement warningMessage;
#FindBy(xpath = "someXpathExpression") private WebElement continueButton;
public void fillForm() throws Exception{
WebElement valueFromDropDown = driver.findElement(By.id("uxMiniFinderVoyageSelect_chzn_o_" + x));
dropDown.click();
valueFromDropDown.click();
if(user will see that warningMessage suddenly apppears){
dropDown.click();
valueFromDropDown.click(); -> this is where I want to click on another value
}else{
contunieButton.click();
Introduce a method to return drop down webelement randomly like below
public WebElement getDropDownValueRandomly() {
Random random = new Random();
int x = random.nextInt(30) + 1;
WebElement valueFromDropDown = driver.findElement(By.id("uxMiniFinderVoyageSelect_chzn_o_" + x));
return valueFromDropDown;
}
Your Class will be like :
public class SomeClassName{
#FindBy(xpath = "someXpathExpression") private WebElement dropDown;
#FindBy(xpath = "someXpathExpression") private WebElement warningMessage;
#FindBy(xpath = "someXpathExpression") private WebElement continueButton;
public void fillForm() throws Exception{
WebElement valueFromDropDown = getDropDownValueRandomly();
dropDown.click();
valueFromDropDown.click();
if(user will see that warningMessage suddenly apppears){
dropDown.click();
getDropDownValueRandomly().click(); -> this is where I want to click on another value
}else{
contunieButton.click();
}
}
public WebElement getDropDownValueRandomly() {
Random random = new Random();
int x = random.nextInt(30) + 1;
WebElement valueFromDropDown = driver.findElement(By.id("uxMiniFinderVoyageSelect_chzn_o_" + x));
return valueFromDropDown;
}
}
Hope this helps

Cash register java using a random number generator and queue structure

Im trying to make a simulation of a random number of customers going to the cash register. Each cash register can only hold 10 customers. During each random wave a customer is attended from a maximum of 5 lines.
Random rand = new Random(20041995);
for (int j = 0; j < 10; j++)
{
int pick = rand.nextInt(10);
System.out.println(pick);
}
This is the RNG i'm using and I'm trying to integrate into a standard queue structure that adds and deletes items in a list.
This might point you in the right direction:
public static void main(String[] args) {
Random randomCustomer = new Random();
List<Integer> generatedCustomers = new ArrayList<Integer>();
//counter went up to 50 because each register holds 10 people
for(int counter=1; counter<=50;counter++) {
int customer = randomCustomer.nextInt(20041995);
//the random generated customers were then added
generatedCustomers.add(customer);
}
//used the sublist method once i got the size of the array and split it into 5 parts
for (int start =0; start < generatedCustomers.size(); start += 10) {
int end = Math.min(start + 10, generatedCustomers.size());
List<Integer> sublist = generatedCustomers.subList(start, end);
System.out.println("cash register" + " " + sublist);
}
}
}
My output generated this:
cash register [15365553, 2870686, 8239263, 490486, 10449085, 16420026, 3718359, 5010717, 2638567, 14760837]
cash register [20040371, 16869399, 1942712, 14737317, 17357726, 4508897, 4992677, 5038990, 13511211, 8336697]
cash register [4280460, 8933691, 3284599, 17767919, 16640768, 16720106, 2914768, 10021216, 576433, 14489405]
cash register [10122975, 4817494, 18802466, 8706075, 6488663, 10421329, 13197130, 6107886, 7547101, 7711809]
cash register [10627697, 9371901, 7711935, 15270912, 13733952, 12334688, 7676836, 4582069, 10586241, 11101172]

How to set the Id of new added radioButton in java file in android?

I am adding RadioButtons in my view by using a for loop, now I want to set a unique ID for each RadioButton.
for (int item = 0; item < 5; item++) {
child = new RadioButton(this);
itemRadioGroup.addView(child);
child.setId(item);
}
Toast.makeText(getApplicationContext(),
String.valueOf(child.getID()), Toast.LENGTH_SHORT).show();
I want to set the ID of first button as 1, second button as 2, third as 3 and so on. But when I try to display the ID with a Toast message it shows me some garbage value rather than my set ID. How can I set ID properly?
I think it is because 0 is not a integer and your a giving an id of button as 0. where as the ids can only be positive integers..
RadioButton child[]=new RadioButton[5];
for (int item = 1; item <= 5; item++) {
child[i]= new RadioButton(this);
itemRadioGroup.addView(child[i]);
child[i].setId(item);
Toast.makeText(getApplicationContext(),child.getID()+ " ", Toast.LENGTH_SHORT).show();
}
//gets the checked radiobuttons ids
for (int item = 1; item <= 5; item++) {
if(child[i].isChecked()){
Toast.makeText(getApplicationContext(),child[i].getID()+ " ", Toast.LENGTH_SHORT).show();
}
}

Categories