Selenium WebDriver: How I can select links randomly? - java

I need to automate login on website and then choosing links randomly from the list of links. After each test run, new link should be selected randomly from list.
I have already automate login:
public class Test1{
public static void main(String[] args)
String path = System.getProperty("user.dir");
System.out.println(path);
System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"\\ChromeDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get ("http://test.com");
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("brr#gmai.com");
WebElement password = driver.findElement(By.id("pass"));
password.sendKeys("1111");
Now, I have list of links and need to select them randomly. How could I do it ?

To get list of links use driver.findElements(By.tagName("a")) and then to select one at random use a random number generator and select the WebElement at the array index.
http://docs.seleniumhq.org/docs/03_webdriver.jsp

Try this
Random r = new java.util.Random();
List<WebElement> links = driver.findElements(By.tagName("a"));
WebElement randomElement = links.get(r.nextInt(links.size()));

Related

How to select last option on dynamic list using Selenium and Java

How to select last option on dynamic list Using Selenium and Java if I have a list with option that going to expend with new options every time.
List options WebElement examples:
//div[#id='transaction-history-view']/div[#id='accordion']/div[1]/div[#role='tab']//a[#role='button']
//div[#id='transaction-history-view']/div[#id='accordion']/div[2]/div[#role='tab']//a[#role='button']
//div[#id='transaction-history-view']/div[#id='accordion']/div[3]/div[#role='tab']//a[#role='button']
//div[#id='transaction-history-view']/div[#id='accordion']/div[4]/div[#role='tab']//a[#role='button']
See if this works. Get all the options in the list and size()-1 will get the last index to select the last element.
Select select = new Select(driver.findElement(By.xpath("your xpath for select element")));
List<WebElement> allOptions = select.getOptions();
int index = allOptions.size();
select.selectByIndex(index-1);
Based on your example I wrote this:
String xpathLastDiv = "(//div[#id='transaction-history-view'] /div[#id='accordion'] /div)[last()]"
String xpathLastButton = xpathLastDiv + "/div[#role='tab'] //a[#role='button']";
WebDriverWait webDriverWait = new WebDriverWait(driver, 10); //seconds
WebElement lastButton = webDriverWait.until(
ExpectedConditions.elementToBeClickable(
By.xpath(xpathLastButton)
)
);
lastButton.click();

Reach for the deep nested element using Selenium WebDriver (Java)

I looked through a lot of topics on Stackoverflow and tried several recommendations but could hardly succeed in resolving my particular case. I'm trying to automate Google Cloud Pricing Calculator using Selenium WebDriver + Java. I need insert the Number of instances (the first input area on the page) using Java code.
My Java code is following:
WebDriver driver = new ChromeDriver();
driver.get("https://cloud.google.com/products/calculator");
new WebDriverWait(driver, 10)
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//iframe[contains (#name, 'goog_')]")));
WebElement document = driver.findElement(By.xpath("//iframe[contains (#name, 'goog_')]"));
var iframe = document.findElement(By.xpath("//iframe[#id='myFrame']"));
var input = iframe.findElement(By.xpath("//input[#id='input_66']"));
input.click();
input.sendKeys("4");
But NoSuchElementException is thrown when I launch the code: "no such element: Unable to locate element: {"method":"xpath","selector":"//iframe[#id='myFrame']"}.
Xpath is correct but this element is hidden deep into html tree. How can I reach for the element (Number of instances) in this particular case? Thank you in advance!
You first need to switch to the parent iframe element, then switch into the inner iframe and only after that try accessing the input element.
I see you tried to locate the iframe elements but you do not switch into them.
Try this:
WebDriver driver = new ChromeDriver();
driver.get("https://cloud.google.com/products/calculator");
//Find and switch to outer iframe
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//iframe[contains(#src,'product')]")));
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(#src,'product')]")));
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[#id='myFrame']")));
WebElement input = driver.findElement(By.xpath("//input[#id='input_66']"));
input.click();
input.sendKeys("4");
Can you try with the below line of code?
WebDriver driver = new ChromeDriver();
driver.get("https://cloud.google.com/products/calculator");
new WebDriverWait(driver, 10)
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//iframe[contains (#name, 'goog_')]")));
WebElement document = driver.findElement(By.xpath("//iframe[contains (#name, 'goog_')]"));
driver.switchTo().frame(document).switchTo().frame("myFrame");
//var iframe = document.findElement(By.xpath("//iframe[#id='myFrame']"));
WebElement ele = driver.findElement(By.xpath("//input[#id='input_66']"));
ele.click();
ele.sendKeys("4");

How to add 4 best seller item to add to cart in Amazon.com for headphones

I'm stuck in automation of Amazon.com
Steps to automate :
Open www.amazon.com website.
Enter the text “Headphones” in the search box. Hit enter
From the results displayed on page1 add all the items marked as “Best seller” to the cart. 
Code I have tried :
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\****\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.amazon.com");
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement searchBox = wait.until(ExpectedConditions.elementToBeClickable(By.id("twotabsearchtextbox")));
searchBox.click();
searchBox.sendKeys("Headphones"+Keys.ENTER);
Actions action = new Actions(driver);
List<WebElement> bestSellers = driver.findElements(By.xpath("//span[text()='Best Seller']/ancestor::div[#class='sg-row']/following-sibling::div[#class='sg-row']/child::div[1]"));
for(int i=1;i<=bestSellers.size();i++) {
action.moveToElement(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()='Best Seller']/ancestor::div[#class='sg-row']/following-sibling::div[#class='sg-row']/child::div['"+i+"']")))).build().perform();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Best Seller']/ancestor::div[#class='sg-row']/following-sibling::div[#class='sg-row']/child::div['"+i+"']"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("add-to-cart-button"))).click();
//System.err.println(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h2[contains(text(),'Added to Cart')]"))).getText());
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.uss-o-close-icon.uss-o-close-icon-medium"))).click();
driver.navigate().back();
driver.navigate().refresh();
System.err.println("try to find next best seller item ");
}
}
It is adding the first best seller item for all iteration. But I want to add all the 4 best selling product to cart.
Any help will be appreciated.
In code below, xpath used to get all best seller items without sponsored(duplicates) ones. Using stream get href attribute from best seller elements. Iterating best sellers navigate to url, add to the cart and wait for a success message:
import org.openqa.selenium.support.ui.ExpectedConditions;
//...
List<WebElement> bestSellers = driver.findElements(
By.xpath("//span[text()='Best Seller']" +
"/ancestor::div[#data-asin and not(.//span[.='Sponsored'])][1]" +
"//span[#data-component-type='s-product-image']//a"));
List<String> bestSellersHrefs = bestSellers.stream()
.map(element -> element.getAttribute("href")).collect(Collectors.toList());
bestSellersHrefs.forEach(href -> {
driver.get(href);
wait.until(elementToBeClickable(By.id("add-to-cart-button"))).click();
boolean success = wait.until(or(
visibilityOfElementLocated(By.className("success-message")),
visibilityOfElementLocated(By.xpath("//div[#id='attachDisplayAddBaseAlert']//h4[normalize-space(.)='Added to Cart']")),
visibilityOfElementLocated(By.xpath("//h1[normalize-space(.)='Added to Cart']"))
));
});
It seem like you wrong placement increase count i, you can try this :
action.moveToElement(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//span[text()='Best Seller']/ancestor::div[#class='sg-row']/following-sibling::div[#class='sg-row']/child::div[1])[" +i +"]")))).build().perform();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//span[text()='Best Seller']/ancestor::div[#class='sg-row']/following-sibling::div[#class='sg-row']/child::div[1])[" +i +"]"))).click();
And close button, you can use this locator :
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(#class,'uss-o-close-icon uss-o-close-icon-medium') or contains(#class,'a-link-normal close-button')]"))).click();
I look each close button don't have the same locator, here also has its challenges.

Cant sendKeys into ebay username field using WebDriver Selenium 3 with Java and chrome

I have been unable to sendKeys text into the username and password field on ebay.
Here is the code:
WebDriver driver = null;
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
driver = new ChromeDriver();
driver.get("http://www.ebay.co.uk");
WebElement myEbay = driver.findElement(By.linkText("My eBay"));
myEbay.click();
WebElement signInForm = driver.findElement(By.id("SignInForm"));
if (signInForm.isDisplayed())
System.out.println("Sign in form is displayed");
WebElement username;
username = driver.findElement(By.cssSelector("input[placeholder=\"Email or username\"]"));
It manages to find the My Ebay link, and verifies that the sign in form exists but the the username and password fields id's change after every refresh of the page.
The username cssSelector seems to be the problem??
EDIT: I have been successful using XPath but this excercise was to make the cssSelector work as there is no reason in theory why it shouldn't!
I have replaced the cssSelector locator with xpath and it is working fine with absolute xpath. Here is the modified code:
WebDriver driver = null;
System.setProperty("webdriver.chrome.driver", "C:\\Users\\vikas\\workspaceNeon\\Eclipse Soft\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://www.ebay.co.uk");
WebElement myEbay = driver.findElement(By.linkText("My eBay"));
myEbay.click();
WebElement signInForm = driver.findElement(By.id("SignInForm"));
if (signInForm.isDisplayed())
System.out.println("Sign in form is displayed");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebElement username = driver.findElement(By.xpath("html/body/div[4]/div/div/div/div[5]/div/div[1]/div/div[1]/div[1]/div[2]/div/span/form/div[1]/div[5]/div/div[4]/span[2]/input"));
username.sendKeys("Vikas");
Select all inputs as a list and search for the right one:
// fld seems to be the class of the input field but looking at all input elements should work too
List<WebElement> inputs = driver.findElements(By.className("fld"));
for (WebElement input: inputs) {
if (inputs.getAttribute("placeholder") == "Email or username") {
// ...
}
}
if the username and password webelements changes frequently find div section in the page using xpath and get the exact xpath of username weblement.
Hope this help..

How to Enter Text in Contact form using selenium Webdriver?

public static void main(String[] args)
{
WebDriver wd = new FirefoxDriver();
wd.manage().window().maximize();
wd.get("http://www.arthritisspecialityclinic.com");
WebElement link=wd.findElement(By.linkText("CONTACTS"));
link.click();
WebElement Name = wd.findElement(By.xpath(".//*[#id='contact-form']/fieldset/label[1]/span[3]"));
Name.sendKeys("sakthivel");
}
I've executed the above code for Enter text in NAME text box under contact Form in website..But the text is not typed in the specific field only shown Blank...No error also shown in web driver...Any one can help me to Fix this....
Your xPath is wrong. You should select the input tag instead of the span tag. Try this:
WebElement name = wd.findElement(By.xpath("//form[#id='contact-form']/fieldset/label[1]/input"));
name.sendKeys("sakthivel");
Suggestion: This would be a cleaner method to select the WebElement.
WebElement name = wd.findElement(By.xpath("//input[#name='name']"));
name.sendKeys("sakthivel");

Categories