I am working on Selenium WebDriver and using Java. If I perform the Logout function it is not finding the element through the ID. Below is the code:
Log.info("Clicking on Logout button");
//driver.findElement(By.id("moreLink")).click();
if(existsElement("logoutLink") == true) {
WebElement menuHoverLink = driver.findElement(By.id("logoutLink"));
actions.moveToElement(menuHoverLink).click().perform();
Thread.sleep(6000);
}
else {
Log.info("element not present");
System.out.println("element not present -- so it entered the else loop");
}
Below is the HTML tag:
<li>
<a id="logoutLink" href="https://10.4.16.159/index/logout/">Log Out</a>
</li>
Try using .size() method in if condition:
if(driver.findElements(By.id("logoutLink")).size() != 0){
or with .isEmpty() along with !:
if(!driver.findElements(By.id("logoutLink")).isEmpty()){
Try this:
1)
actions.moveToElement(menuHoverLink).perform();
menuHoverLink.click;
insted of:
actions.moveToElement(menuHoverLink).click().perform();
Thread.sleep(6000);
OR
2) New method:
clickWhenTheElementIsClickable(By.id("logoutLink"), 10);
...
protected void clickWhenTheElementIsClickable(By locator, long timeout) {
WebDriverWait wait = (WebDriverWait)new WebDriverWait(driver,timeout)
.ignoring(StaleElementReferenceException.class);
WebElement element = wait.until(
ExpectedConditions.elementToBeClickable(locator));
element.click();
}
Related
I'm actually trying to design a test case for element in the span
<div class="one">
Annual Salary
<span>€40,000</span>
</div>
My code is:
String expected = "€40,000";
WebElement resultTextBox = MyDriver.findElement(By.cssSelector("#results1 > div.wrapper > div.one > span"));
String TestResult = resultTextBox.getText();
if (expected.equalsIgnoreCase(TestResult)) {
System.out.println("Test Case Pass");
}
else
{
System.out.println("Test Case failed");
MyDriver.close();//close
}
Use the following code for WebElement that contains span text as xpath:
WebElement resultTextBox = MyDriver.findElement(By.xpath("//span[text()='€40,000']"));
I am having problem with locating WebElement using different locators. In the below html tag I tried locating the "write a review" WebElement with different locators like linkText,xpath,classname but still getting NoSuchElementException
-->url https://www.tripadvisor.in/-->search for Club Mahindra-->click on Club Mahindra-->click on write a review.
<a href="/UserReview-g641714-d1156207-Club_Mahindra_Madikeri_Coorg-
Madikeri_Kodagu_Coorg_Karnataka.html" target="_blank" class="ui_button
primary">Write a review</a>
Locators used
By.xpath("//*[#id="component_12"]/div/div[2]/div/div[2]/div/div[1]/a")
By.xpath("//a[#href='/UserReview-g641714-d1156207-
Club_Mahindra_Madikeri_Coorg-Madikeri_Kodagu_Coorg_Karnataka.html']")
By.className("ui_button primary")
By.linkText("Write a review")
I am really confused. What am I doing wrong?
I have tired to analyse and implement the same. Below are my findings:
-> Application waiting time is more as there are lots of dynamic loads applicable for the page.
-> Proper waits needs to be implemented
-> Check whether all the pages are getting opened in the same tab or clicking on each link is redirecting to new tabs, if so then we have to switch to that particular window.
-> Below code works like a pro for me.
driver.get("https://www.tripadvisor.in/");
WebDriverWait wait = new WebDriverWait(driver, 120);
WebElement ele1 =
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[text()='Where to?']")));
ele1.click();
WebElement ele2= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#placeholder='Where to?']")));
ele2.sendKeys("club mahindra, india");
WebElement ele3= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Search for ')]")));
ele3.click();
WebElement ele4= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Club Mahindra Madikeri, Coorg')]")));
ele4.click(); //this click leads to a new tab
Set<String> winHandles = driver.getWindowHandles();
for(String str : winHandles) {
driver.switchTo().window(str);
}
System.out.println(driver.getTitle());
WebElement ele;
int i=1;
while(true) {
try {
ele = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[text()='Write a review']")));
break;
}catch(Exception e) {
System.out.print(i++);
}
}
System.out.println();
Actions action = new Actions(driver);
action.moveToElement(ele);
ele.click();
System.out.println("Clicked on the 'Write a review button'");
you can try
//a[contains(text(),'Write a review')]
I'm trying to submit an application on indeed using Selenium WebDriver.
I've entered jobType, and jobLocation, pressed search, opened up first result, and in new tab, switched focus, and pressed apply. Now, a pop up appears changing the previously 1 iframe on page to 2. I switch to second iframe and then try to send keys to input text field of "name" yet no input field exists
driver.get("https://www.indeed.com");
WebElement what = driver.findElement(By.id("text-input-what"));
what.sendKeys("Java Programmer");
WebElement where = driver.findElement(By.id("text-input-where"));
Thread.sleep(500);
for (int i = 0; i < 20; i++) {
where.sendKeys(Keys.BACK_SPACE);
}
where.sendKeys("Toronto, ON");
WebElement submit = driver.findElement(By.xpath("//button[#class='icl-Button icl-Button--primary icl-Button--md icl-WhatWhere-button']"));
submit.click();
WebElement thirdElement = driver.findElement(By.xpath("/html[1]/body[1]/table[2]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[2]/div[9]"));
thirdElement.click();
System.out.println(driver.getWindowHandle());
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
Thread.sleep(3000);
WebElement apply = driver.findElement(By.xpath("//button[#class='icl-Button icl-Button--branded icl-Button--md']//div[#class='jobsearch-IndeedApplyButton-contentWrapper'][contains(text(),'Apply Now')]"));
System.out.println(driver.findElements(By.tagName("iframe")).size());
apply.click();
driver.manage().window().maximize();
Thread.sleep(3000);
System.out.println(driver.getWindowHandle());
driver.switchTo().frame(1);
System.out.println(driver.getWindowHandle());
// Thread.sleep(3000);
System.out.println(driver.findElements(By.tagName("iframe")).size());
WebElement inputName = driver.findElement(By.xpath("//input[#id='input-applicant.name']"));
inputName.sendKeys("Adam Smith");
html code on ref page
.
Target indeed Page
The expected results are that i can input text to text field, and the actual is that it gives error message:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//input[#id='input-applicant.name']"}
(Session info: chrome=76.0.3809.87)
To achieve the inputName, you must switch the frame two times, please try this code to achieve what you mean :
driver.get("https://www.indeed.com");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text-input-what")));
WebElement what = driver.findElement(By.id("text-input-what"));
what.sendKeys("Java Programmer");
WebElement where = driver.findElement(By.id("text-input-where"));
for (int i = 0; i < 20; i++) {
where.sendKeys(Keys.BACK_SPACE);
}
where.sendKeys("Jakarta");
WebElement submit = driver.findElement(By.xpath("//button[#class='icl-Button icl-Button--primary icl-Button--md icl-WhatWhere-button']"));
submit.click();
wait.until(ExpectedConditions.elementToBeClickable(By.className("title")));
WebElement thirdElement = driver.findElement(By.className("title"));
thirdElement.click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(text(),'Apply Now')]")));
WebElement apply = driver.findElement(By.xpath("//*[contains(text(),'Apply Now')]"));
apply.click();
driver.manage().window().maximize();
Thread.sleep(1000);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("[src^='https://apply.indeed.com/indeedapply/x'")));
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("[src^='https://apply.indeed.com/indeedapply/resume']")));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='input-applicant.name']")));
WebElement inputName = driver.findElement(By.xpath("//input[#id='input-applicant.name']"));
inputName.sendKeys("Adam Smith");
Thread.sleep(2000);
I'm trying to select an item on a listbox. The following code works when debugging the application but not on a normal run (as JUnit test)
wait.until(ExpectedConditions.elementToBeClickable(
By.xpath("//div[#id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span")
));
driver.findElement(
By.xpath("//div[#id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span")
).click();
wait.until(ExpectedConditions.elementToBeClickable(
By.xpath("//ul[#id='symptomHeadGroupDropDown_listbox']/li[5]")
));
driver.findElement(
By.xpath("//ul[#id='symptomHeadGroupDropDown_listbox']/li[5]")
).click();
Any ideas?
Try this code, it will wait for each second till 60 seeconds to find and click element:
int flag=0,wait=0;
while(flag==0 && wait<60){
try{
driver.findElement(By.xpath("//div[#id='ContentArea']/div/div/div[2]/div/table/tbody/tr[2]/td/div/span/span/span[2]/span")).click();
flag=1;
}
catch(Exception){
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
wait++;
}
}
flag=0,wait=0;
while(flag==0 && wait<60){
try{
driver.findElement(By.xpath("//ul[#id='symptomHeadGroupDropDown_listbox']/li[5]")).click();
flag=1;
}
catch(Exception){
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
wait++;
}
}
My theory would be that the state of the WebElement is changing between your wait.until call and the second time you resolve it to invoke click.
Rather than resolving the WebElement multiple times, call click() on the WebElement return value from your call to the WebDriverWait.
WebElement target1 = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span")));
target1.click();
WebElement target2 =wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[#id='symptomHeadGroupDropDown_listbox']/li[5]")));
target2.click();
Or, if you don't want to store it as a temp var...
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[#id='symptomHeadGroupDropDown_listbox']/li[5]"))).click();
I walk a list of links , I click on them one by one , I go to the page the link and realize the actions that need to perform and then return to the list to click on the next link, it is working perfectly.
What I need now is to come to the end of the links , where the loop ends , the selenium click the forward button to go to the next page and be done again the link count of this page and start the cycle again.
I can not make the selenium click the move because it says that the click(); command You can not be using in a webelento .
The method click () is undefined for the type List < WebElement >
This is the HTML structure:
<div id="results-pagination">
<h2 id="pagination-heading">Pagination</h2>
<ul class="pagination">
<li class="prev">
<a class="page-link" href="url" title="back" data-li-page="1">< back</a>
</li>
<li class="link">
<a class="page-link" href="url" title="page 2" data-li-page="2">2</a>
</li>
<li class="next">
<a class="page-link" href="next" title="next" data-li-page="next"></a>
</li>
</ul>
</div>
selenium code:
List<org.openqa.selenium.WebElement> numberpages= driver.findElements(By.className("page-link"));
System.out.println("numberpages : " + numerospaginas.size());
List<org.openqa.selenium.WebElement> links= driver.findElements(By.linkText("to connect"));
System.out.println("Count to connect : " + links.size());
Thread.sleep(2000);
for(int i=0;i<5;i++){
links= driver.findElements(By.linkText("to connect"));
links.get(i).click();
Thread.sleep(2000);
boolean convite = driver.getPageSource().contains("iweReconnectSubmit");
if(invite == true){
Thread.sleep(2000);
boolean error = driver.getPageSource().contains("message:");
do{
//action
By tipoPlano = By.cssSelector("[name='reason'][value='IF'][type='radio']");
driver.findElement(tipoPlano).click();
}while(error == true);
//submit
driver.findElement(By.name("iweReconnectSubmit")).click();
Thread.sleep(2000);
WebDriverWait confirmacaoadicao = new WebDriverWait(driver, 10);
confirmacaoadicao.until(ExpectedConditions.textToBePresentInElement(By.id("control_gen_3"), "invite for: "));
String pessoa = driver.findElement(By.xpath("//div[#id='control_gen_3']//a")).getText();
System.out.println(pessoa + " add" );
driver.navigate().to(list_of_links);
WebDriverWait retorno = new WebDriverWait(driver, 10);
retorno.until(ExpectedConditions.elementToBeClickable(By.linkText("To connect")));
}
}
//does not work
driver.findElements(By.linkText("next")).click();
//does not work
((org.openqa.selenium.WebElement)driver.findElements(By.linkText("next"))).click();
your click function is not coming because driver.findElements(By.linkText("next")) returns a list List<WebElement> and click() cant be called on a list object .
you can call click method my iterating over the list :
List<WebElement> WebElementList = driver.findElements(By.linkText("next"));
for(WebElement element : WebElementList){
element.click(); // click can be called on object of WebElement
}
I modified the code to iterate through google search results pages and to get the results' URLs.
public static void searchGoogle(String query) throws InterruptedException {
try {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.co.uk");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("\"" + query + "\" filetype:pdf\n");
element.submit();
// wait until the google page shows the result
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
getResults(driver);
Thread.sleep(1000);
for (int i = 0; i < 10; i++) {
driver.findElement(By.linkText("Next")).click();
Thread.sleep(1000);
getResults(driver);
}
} catch (Exception e) {
System.err.println("Error caught - " + e);
}
}
public static void getResults(WebDriver driver) {
List<WebElement> findElements = null;
findElements = driver.findElements(By.xpath("//*[#id='rso']//h3/a"));
for (WebElement webElement : findElements) {
System.out.println(webElement.getAttribute("href"));
}
}
It should be driver.findElement(By.linkText("next")).click();. driver.findElements returns List<WebElement> while driver.findElement returns single WebElement.
Also, it seems the button doesn't have next text. Try looking by class
driver.findElement(By.className("next")).click();
next text will look like
<a class="page-link" href="next" title="next" data-li-page="next">"next"</a>
with next before the <a> closing tag.