Venu
Venu

Reputation: 363

How to locate Element via CSS Selector/XPath?

<a class="LinkDetail" href="/settings/carsettings?xyz=L_11:1:*:2&carid=199&carnumber=4294967295" target="_top" tabindex="23"/>

In the above link, I need to locate element using /settings/carsettings and carid=199

Using a CSS locator. Can anyone let me know the syntax for the same? Also share the syntax for XPath too.

Upvotes: 0

Views: 351

Answers (2)

Yi Zeng
Yi Zeng

Reputation: 32895

Show us what you tried please, so we can anylyse what you failed to achieve. If the following CSS Selector/XPath don't work, post your stacktrace and more HTML code to find the best locators.

CSS Selector

a[href*='settings/carsettings'][href*='carid=199']

XPath

.//a[contains(@href, 'settings/carsettings') and contains(@href, 'carid=199')]

Upvotes: 4

StrikerVillain
StrikerVillain

Reputation: 3786

What you require can be achieved using the following code :-

//get all <a> tags in the webpage to a list
List<WebElements> aTags = driver.findElements(By.tagName("a"));


int index = 0; 
//iterate through list of <a> tags
for (WebElement aTag: aTags) {
    //get the href attribute of each <a> tag
    String href = aTag.getAttribute("href");

    //see if the href contains /settings/carsettings and carid=199
    if (href.contains("/settings/carsettings")&&href.contains("carid=199")) {
        //if it contains break out of for loop. This esssentially gives the index
        break;
    }
    index++;
}

//get the required <a> tag using the index
WebElement required = aTags.get(index);

Let me know if this helps you.

Upvotes: 0

Related Questions