On https://www.zillow.com I am trying to verify search using auto suggestion box.
I have written below code:
public static void verifySearch() {
try {
WebElement searchbar = driver.findElement(By.id("search-box-input"));
searchbar.sendKeys("sea");
// Thread.sleep(10);
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul[#role='listbox']/li")));
List<WebElement> list = driver.findElements(By.xpath("//ul[#role='listbox']//li"));
System.out.println("Total no of suggestions in search box:::====> " + list.size());
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getText());
if (list.get(i).getText().contains("Seattle WA")) {
/*
* JavascriptExecutor js = (JavascriptExecutor)driver;
* js.executeScript("arguments[0].click();", list.get(i));
*/
list.get(i).click();
break;
}
}
System.out.println("out");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
e.printStackTrace();
}
Here for auto suggestion list I am using following xpath but it doesn't work at run time:"//ul[#role='listbox']//li"
Can anybody guide where I am wrong.
Note:on this website autosuggestion is starts to be displayed after 3chars in search field.
Here my friend. Please try to execute the below code. You can now try to fix your issue with this simple solution.
try {
WebElement searchbar = driver.findElement(By.id("search-box-input"));
searchbar.click();
for( char character : "sea".toCharArray() )
{
searchbar.sendKeys(String.valueOf(character));
Thread.sleep(2000);
}
List<WebElement> list = driver.findElements(By.xpath("//ul[#role='listbox']//li"));
System.out.println("Total no of suggestions in search box:::====> " + list.size());
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getText());
if (list.get(i).getText().contains("Seattle WA")) {
/*
* JavascriptExecutor js = (JavascriptExecutor)driver;
* js.executeScript("arguments[0].click();", list.get(i));
*/
list.get(i).click();
break;
}
}
System.out.println("out");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
e.printStackTrace();
}
Related
Generic function for Scroll where scrollablelist is the locator of scroll view in which we have to scroll
public void scrollToElementWithText(RemoteWebDriver driver, String scrollableList, String text) {
MobileElement element = (MobileElement) driver
.findElement(MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().resourceId(\""
+ scrollableList + "\")).scrollIntoView(" + "new UiSelector().text(\"" + text + "\"))"));
}
You can try below code with in existing code scrollable(true).instance(0))
Add in desired capability UiAutomator2 if you are using appium as automation engine.
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2");
Now use below functions if you have element's id, and index as 0 for there is one element on page.
public void scrollByID(String Id, int index) {
try {
driver.findElement(MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().resourceId(\""+Id+"\").instance("+index+"));"));
} catch (Exception e) {
e.printStackTrace();
}
}
Scroll using Text
public void scrollByText(String menuText) {
try {
driver.findElement(MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textMatches(\"" + menuText + "\").instance(0));"));
} catch (Exception e) {
e.printStackTrace();
}
}
Scroll using help of screen size:
public void scrollToBottom() {
int x = driver.manage().window().getSize().width / 2;
int start_y = (int) (driver.manage().window().getSize().height * 0.2);
int end_y = (int) (driver.manage().window().getSize().height * 0.8);
TouchAction dragNDrop = new TouchAction(driver)
.press(PointOption.point(x,start_y)).waitAction(WaitOptions.waitOptions(Duration.ofMillis(500)))
.moveTo(PointOption.point(x, end_y))
.release();
dragNDrop.perform();
}
After moving to the value which is present in dropdown, i want to get it using actions class. Below is the code i have written. i am trying to print the dropdown values. HTML tag for dropdown is input(for select i have code). Please help me
public static void caseSearch()
{
try
{
Actions a=new Actions(driver);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
logger.info("clicking on cases tab :: ");
driver.findElement(By.xpath(loader.getProperty(Constants.CaseTab))).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement ele=driver.findElement(By.xpath(loader.getProperty(Constants.CaseSearch)));
ele.click();
for(int i=0;i<=20;i++)
{
//i want to print the first value of dropdown in console
a.sendKeys(Keys.DOWN,Keys.DOWN,Keys.DOWN).build().perform();
String value=ele.getText();
System.out.println("value is = "+value);
a.sendKeys(Keys.DOWN,Keys.DOWN).build().perform();
Thread.sleep(3000);
a.sendKeys(Keys.ENTER).build().perform();
}
}
catch(Exception e)
{
logger.info("case search method is not executed :: " +e);
}
}
I think you forgot to get the value from the dropdown box.
You need to use the Select Class to get it.
Actions key = new Actions(browser);
WebElement dropdownElement = this.browser.findElement(By.xpath("YOUR DROPDOWN ELEMENT"));
Select dropOptions = new Select(dropdownElement);
int elements = dropOptions.getOptions().size();
for (int i = 0; i < elements; i++) {
dropdownElement.click();
if (i > 0) {
Thread.sleep(1000L);
key.sendKeys(Keys.DOWN).build().perform();
Thread.sleep(1000L);
key.sendKeys(Keys.ENTER).build().perform();
}
else {
Thread.sleep(1000L);
ActionPerformers.sendActionKey(browser, Keys.ENTER);
}
System.out.println("ELEMENT " + i + " -> " + dropOptions.getFirstSelectedOption().getText()); //Here you will get the selected Value...
}
This is only an exemple, I hope it suits you.
I m sending the firepath screenshot
I want to select first element and display in element text box
Can someone please help in this
You can update your code as below:
public class SelectAutoSugggestedValue {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.google.com");
driver.findElement(By.id("gbqfq")).sendKeys("automation tutorial");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
List allOptions = driver.findElements(By.xpath("//td/span[text()='automationtutorial']"));
for (int i = 0; i < allOptions.size(); i++) {
String option = allOptions.get(i).getText();
System.out.println(option);
}
}
}
Problems with some Automation Testing using Before / After / Test
I'm getting stuck at the browser window, no test is executed...
Not sure why this doesn't work. I've exported some tests from Selenium IDE, exported as Java, edited that stuff in Eclipse, yet still it doesn't work...
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Checkimage {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testCheckimage() throws Exception {
driver.get("http://");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.linkText("sign in / up"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.id("login-email")).clear();
driver.findElement(By.id("login-email")).sendKeys("michael.sinitsin#avid.com");
driver.findElement(By.id("login-password")).clear();
driver.findElement(By.id("login-password")).sendKeys("mike1780");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if ("sign in".equals(driver.findElement(By.id("login-buttons-password")).getText())) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.id("login-buttons-password")).click();
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if ("Tester".equals(driver.findElement(By.linkText("Tester")).getText())) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.linkText("Tester")).click();
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.id("inputScoreUrl"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.id("inputScoreUrl")).sendKeys("http://www.sheetmusicdirect.com/scorches/smd_000001.sco");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if ("Enter a URL to a publicly accessible SCO file. No need to URL encode it, just copy and paste it in.".equals(driver.findElement(By.cssSelector("p.help-block")).getText())) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.id("submitScoreView")).click();
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.cssSelector("img"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
try {
assertTrue(isElementPresent(By.cssSelector("img")));
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
Not sure why this doesn't work. I've exported some tests from Selenium IDE, exported as Java, edited that stuff in Eclipse, yet still it doesn't work...
Dear Michael Sinitsin,
As I see it you have here several issues:
You do not supply a valid URL to the web driver
replace driver.get("http://"); with a valid URL like driver.get("http://www.google.com");
You are exposing your user/password on a public site
Michael Sinitsin,
you should first mention proper URl driver.get("http://"); And your script is too complex,you could write it in a simplest way.
I am new to selenium and was trying to make my work automated. My results consists of pagination like next page. At last page "Next" button is disabled and my code should not access that particular element.
List<WebElement> pagesize = driver.findElements(By.xpath("html/body/div[1]/div[3]/div[3]/div/span"));
while(true) {
for(int i=5; i<=pagesize.size(); i++) {
WebElement Analystelem = driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
List<WebElement> pagesize = driver.findElements(By.xpath("html/body/div[1]/div[3]/div[3]/div/span"));
System.out.println(pagesize.size());
while(true) {
for(int i=5;i<=pagesize.size();i++) {
WebElement Analystelem = driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
if(elementpage.isEnabled()) {
elementpage.click();
}
else {
System.exit(1);
}
note: older search is the next button here.
at last page of results i am getting an exception as
"Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"html/body/div[1]/div[3]/div[3]/div[10]/span"}"
First of all I doubt that you have searched for a span and stored its reference to 'Analystelem' but you are calling a click action on 'elementpage'.
If the code you provided is working than below given code will work fine. When Selenium will find the element and tries to click on it; it will throw exception, handle the exception as you feel best but it will not break your execution.
Just put your code in Try Catch block like this:
while(true)
{
for(int i=5;i<=pagesize.size();i++)
{
WebElement Analystelem=driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
if(elementpage.isEnabled())
{
Try
{
elementpage.click();
}
Catch (Exception ex)
{
//Do whatever you want to do here
}
}
else
{
System.exit(1);
}
}
}
Additionally, you do not have to check weather the element is enabled or not. Let the try catch do its work. More suited code:
while(true)
{
for(int i=5;i<=pagesize.size();i++)
{
WebElement Analystelem=driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
Try
{
elementpage.click();
}
Catch (Exception ex)
{
System.exit(1);
//Do whatever you want to do here
}
}
}