WebDriver driver = new FirefoxDriver();
driver.get("https://www.ignitionone.com/company/careers/");
driver.manage().window().maximize();
Thread.sleep(2000);
driver.findElement(By.cssSelector("button.teal")).click();
Thread.sleep(2000);
String s2 =driver.findElement(By.cssSelector("#board_title")).getText();
List<WebElement>d_details = driver.findElements(By.cssSelector(".level-0"));
for(int i=0; i<d_details.size();i++){
WebElement element = d_details.listIterator();
String innerhtml = element.getAttribute("innerHTML");
System.out.println("Available openings are" + innerhtml);
}
System.out.println("The title is " + s2);
driver.quit();
This is my code.I am trying to print the available job openings in different areas in the webpage. Can someone please help to understand whats going wring in here.
You have a type casting problem on this line:
WebElement element = d_details.listIterator();
A better way to iterate over the elements would be this:
List<WebElement> results = driver.findElements(By.cssSelector(".level-0"));
for (WebElement result: results) {
String innerhtml = result.getAttribute("innerHTML");
System.out.println("Available openings are" + innerhtml);
}
Note that you may also be experiencing a timing issue. You should replace your Thread.sleep() calls with Explicit Wait commands, check out this topic:
WebDriver - wait for element using Java
Related
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.
I am trying to navigate to "https://developers.google.com/".
I then click a link by the xpath and redirect to another page.
Everything works as far as finding elements and clicking links on the first page.
But I cannot seem to find the elements I want to look for after I go to the new page.
The redirected page is "https://cloud.withgoogle.com/next18/sf/?utm_source=devsite&utm_medium=hpp&utm_campaign=cloudnext_april18"
This is checking if text is equal.
confirmText("Imagine", "//*[#id=\"main\"]/span/div[2]/div/div/div[1]/div[1]/div/div[1]/div[2]/h3");
public static void confirmText(String text, String xpath) {
System.out.println("Trying to confirm that given string is equal to the text on page.");
WebElement element = driver.findElement(By.xpath(xpath));
System.out.println("Test case: " + text);
System.out.println("Result: " + element.getText());
if (element.getText() == text) {
System.out.println("\nEquals.");
}
else {
System.out.println("\nDoes not equals.");
}
System.out.println("\n\n");
}
This is sending keys.
public static void sendKeys() {
WebElement firstname = driver.findElement(By.id("firstName"));
firstname.sendKeys("John");
WebElement lastname = driver.findElement(By.xpath("//*[#id=\"lastName\"]"));
lastname.sendKeys("Doe");
WebElement email = driver.findElement(By.xpath("//*[#id=\"email\"]"));
email.sendKeys("johndoe#gmail.com");
WebElement jobtitle = driver.findElement(By.xpath("//*[#id=\"jobTitle\"]"));
jobtitle.sendKeys("Software Engineer");
WebElement company = driver.findElement(By.xpath("//*[#id=\"company\"]"));
company.sendKeys("ABCD");
}
The error is
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id="main"]/span/div[2]/div/div/div[1]/div[1]/div/div[1]/div[2]/h3"}
Only the first page actually waits to finish loading before the script starts. If you navigate away form the page then you will need to manually wait. Without waiting, the script will continue to the next command immediately after clicking the link that changes the page, and since the page is not loaded yet you will not find the element. This gives the error.
The simplest way to wait is by using "WebDriverWait"
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(>someid>)));
There are more simple examples here:
http://toolsqa.com/selenium-webdriver/wait-commands/
You can try this xpath using for imagine and put some wait as #chris mentioned
//div//h3[contains(text(),'Imagine')]
JavascriptExecutor can be used to get the value of an element,
Refer code,
confirmText("Imagine", "//*[#id=\"main\"]/span/div[2]/div/div/div[1]/div[1]/div/div[1]/div[2]/h3");
public static void confirmText(String text, String xpath) {
System.out.println("Trying to confirm that given string is equal to the text on page.");
WebElement element = driver.findElement(By.xpath(xpath));
JavascriptExecutor executor = (JavascriptExecutor)driver;
System.out.println("Test case: " + text);
System.out.println("Result: " + executor.executeScript("return arguments[0].innerHTML;", element););
if (text.equals(executor.executeScript("return arguments[0].innerHTML;", element))) {
System.out.println("\nEquals.");
}
else {
System.out.println("\nDoes not equals.");
}
System.out.println("\n\n");}
I struggle with the problem of not being able to switch between tabs using the loop in Selenium WebDriver. I can do this at once, but I need to use the code repeatedly, in a loop.
Here comes the error:
"Exception in thread" main "org.openqa.selenium.NoSuchWindowException: Unable to locate window"
My code can find all the elements, open a link in a new tab, close it. However, it can not perform this operation again with the next element.
Here is my code( I'm using Firefox):
List<WebElement> allElements = driver.findElements(By.className("_4zhc5"));
int s = allElements.size();
System.out.println("total users to check: " + allElements.size());
for (int i = 0; i < s; i++) {
allElements = driver.findElements(By.className("_4zhc5"));
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
allElements.get(i).sendKeys(selectLinkOpeninNewTab);
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
Thread.sleep(3000);
}
driver.close();
Thread.sleep(2000);
}
I also created a prototype page using jsfiddle. The error appears on the second attempt to execute the code. Just the script does not click on another element called "lovely"
You need to switch back to the original window where the links are.
Click on one if the links
Switch to that tab
Close tab
Switch back to default window where you are getting the links
Easiest way is to store the "original" window and switch back to that one all the time.
winHandleBefore = driver.getWindowHandle();
when closing the tab
driver.close();
driver.switchTo().window(winHandleBefore)
/*the second "for loop" will not help you so u should use another logic with another condition it will switch using while loop and hasNext method
try it: */
List allElements = driver.findElements(By.className("_4zhc5"));
int s = allElements.size();
System.out.println("total users to check: " + allElements.size());
for (int i = 0; i < s; i++) {
allElements = driver.findElements(By.className("_4zhc5"));
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
allElements.get(i).sendKeys(selectLinkOpeninNewTab);
Set<String>windowat=driver.getWindowHandles();
Iterator<String>itro=windowat.iterator();
while(itro.hasNext()) {
String currntpage=itro.next();
driver.switchTo().window(currntpage);
String thetitle=driver.getTitle();
System.out.println(thetitle); }
Following is short program & in the following web site:
https://uk.webuy.com/search/index.php?stext=*§ion=&catid=956
I am trying to click the first three product's "I want to buy this item" button &
view them in the VIEW BASKET at the right side of the page.
For some reason, I am able to see the second and third product only. For some reason, the first product never makes it to the basket, & it does not produce an error.
Only when I change the following line:
allButtons.get(0).click();
to:
allButtons.get(0).click();
allButtons.get(0).click();
allButtons.get(0).click();
I will see one occurrence of the first product in the basket.
What am I doing wrong? Is there something missing that is causing this problem?
Using Java 1.8
Selenium WebDrive Version #2.48
Mac OS Version #10.11.13
Thank you
public class ZWeBuy {
static WebDriver driver;
#Test
public void testProductPurchaseProcess() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://uk.webuy.com/search/index.php?stext=*§ion=&catid=956");
closePopupIfPresent();
//xpath for all product names in this page
List<WebElement> allNames = driver.findElements(By.xpath("//div[#class='searchRecord']/div[2]/h1/a"));
List<WebElement> allButtons = driver.findElements(By.xpath("//div[#class='action']/div/a[2]/div/span"));
System.out.println("Total names = "+ allNames.size());
System.out.println("Total buttons = "+ allButtons.size());
System.out.println("I= " + 0 + " PRDCT: --- " +allNames.get(0).getText());
allButtons.get(0).click();
WebDriverWait wait = new WebDriverWait(driver,120);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("html/body/div[5]/div[1]/div[3]/div[5]/div[1]/div[1]/div[3]/div/a[2]/div/span")));
System.out.println("I= " + 1 + " PRDCT: --- " +allNames.get(1).getText());
allButtons.get(1).click();
System.out.println("I= " + 2 + " PRDCT: --- " +allNames.get(2).getText());
allButtons.get(2).click();
}
public static void closePopupIfPresent(){
Set<String> winIds = driver.getWindowHandles();
System.out.println("Total windows -> "+ winIds.size());
if(winIds.size() == 2){
Iterator<String> iter = winIds.iterator();
String mainWinID = iter.next();
String popupWinID = iter.next();
driver.switchTo().window(popupWinID);
driver.close();
driver.switchTo().window(mainWinID);
}
}
}
Your code isn't functional. Popup closing logic doesn't work, its actually not a separate window, its a dialog box within the same window. You should also consider simplifying your selectors. Alright enough said, here is working and tested code.
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get("https://uk.webuy.com/search/index.php?stext=*§ion=&catid=956");
WebElement element;
try {
element = driver.findElement(By.cssSelector(".deliver-component-wrapper>a>div"));
System.out.println("Closing pop up");
element.click();
} catch (NoSuchElementException e) {
System.out.println("Alright, no such dialog box, move on");
}
List<WebElement> buyButtons = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector(
"span.listBuyButton_mx")));
Assert.assertTrue("Less than three buttons found", buyButtons.size() >= 3);
for (int i = 0; i < 3; i++) {
WebElement buyButton = buyButtons.get(i);
wait.until(ExpectedConditions.elementToBeClickable(buyButton)).click();
System.out.println("Clicked Buy Button " + (i + 1));
}
WebElement basketCount = wait
.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#buyBasketRow>td.basketTableCell")));
System.out.println(basketCount.getText());
driver.quit();
It prints
Closing pop up
Clicked Buy Button 1
Clicked Buy Button 2
Clicked Buy Button 3
3 item/s
Your browser could not render that first button. you may put wait.until() method before each click event.
try this
WebDriverWait wait = new WebDriverWait(driver,120);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/div[5]/div[1]/div[3]/div[5]/div[1]/div[1]/div[3]/div/a[1]/div/span")));
allButtons.get(0).click();
I am creating an automatic test for some webs and I'm using WebDriver, TestNG and code that is written in Java. On the page is shown register of categories, in parentheses is number of auctions and i need to get this number as variable.
I use this code
By bycss =By.cssSelector(".list.list-categories>li:first-child");
WebElement number1_1_vse = driver.findElement(bycss );
String text_vse1_1 = number1_1_vse.getText();
but I get only first number and i need to get all. Someone advised me that I should use List. But when i use it, i get only
[[[[[[[FirefoxDriver: firefox on WINDOWS (7e6e0d0f-5cbb-4e48-992f-26d743a321a5)] -> css selector: .list.list-categories>li:first-child]] -> xpath: ..]] -> xpath: .//*], [[[[[[FirefoxDriver: firefox on WINDOWS (7e6e0d0f-5cbb-4e48-992f-.....
code:
By bycss2 =By.cssSelector(".list.list-categories>li:first-child");
WebElement number1_1_vse2 = driver.findElement(bycss2 );
WebElement parent1 = number1_1_vse2.findElement(By.xpath(".."));
List<WebElement> childs1 = parent1.findElements(By.xpath(".//*"));
System.out.println(childs1);
link to the website
screenshot -> image with the number
can anyone advise me please?
Try the following code:
//...
By mySelector = By.xpath("/html/body/div[1]/div/section/div/div[2]/form[1]/div/ul/li");
List<WebElement> myElements = driver.findElements(mySelector);
for(WebElement e : myElements) {
System.out.println(e.getText());
}
It will returns with the whole content of the <li> tags, like:
<a class="extra">Vše</a> (950)</li>
But you can easily get the number now from it, for example by using split() and/or substring().
Try with below logic
driver.get("http://www.labmultis.info/jpecka.portal-exdrazby/index.php?c1=2&a=s&aa=&ta=1");
List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));
for(WebElement ele :allElements) {
System.out.println("Name + Number===>"+ele.getText());
String s=ele.getText();
s=s.substring(s.indexOf("(")+1, s.indexOf(")"));
System.out.println("Number==>"+s);
}
====Output======
Name + Number===>Vše (950)
Number==>950
Name + Number===>Byty (181)
Number==>181
Name + Number===>Domy (512)
Number==>512
Name + Number===>Pozemky (172)
Number==>172
Name + Number===>Chaty (28)
Number==>28
Name + Number===>Zemědělské objekty (5)
Number==>5
Name + Number===>Komerční objekty (30)
Number==>30
Name + Number===>Ostatní (22)
Number==>22
List<WebElement> myElements = driver.findElements(By.xpath("some/path//a"));
System.out.println("Size of List: "+myElements.size());
for(WebElement e : myElements)
{
System.out.print("Text within the Anchor tab"+e.getText()+"\t");
System.out.println("Anchor: "+e.getAttribute("href"));
}
//NOTE: "//a" will give you all the anchors there on after the point your XPATH has reached.