简体   繁体   中英

Not able to click on an element using xpath

I tried to click on an element using CSS selector and later Xpath . But failed both. Can anyone help me in solving the issue. Below is the xpath I provided.

Xpath: //*[@id="content"]/div/div[1]/ul/li[3]/div[2]/div/button

Html: Select or search a country in the list... Bahrain

I am new to Selenium and don't have prior experience in automating applications. Should I stick on using xpath or should try using some other locators?

You can either use JavascriptExecutor :

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element);

Or

Get the xpath of the WebElement . Put them in the List (Java Collection)

List<WebElement> lst = xpath ;
for(WebElement we:lst){
    if(we.getText().equalsIgnoreCase("Bahrain"))
        we.click();
    }
} 

You can use the code below to search for the desired text and click the element.

String searchText = "Bahrain"; // you can parameterize it 
WebElement dropdown = driver.findElement(By.id("content"));
dropdown.click(); // assuming you have to click the "dropdown" to open it
List<WebElement> options = dropdown.findElements(By.tagName("li"));
for (WebElement option : options)
{
    if (option.getText().equals(searchText))
    {
        option.click(); // click the desired option
        break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM