Syed Alam
Syed Alam

Reputation: 35

How to write an XPath or CSS expression?

<span class="left-menu-title selectorgadget_selected" data-xpal="xpath-verify-selected" style="">Admin</span>

How can I write an XPath or CSS expression? I tried the plug-ins does not work.

If anyone knows how to click an item from the left-side bar after log-in to the site will be a great help. it does not click, the script fails.

@FindBy(xpath = "//SPAN[@class='left-menu-title'][text()='Admin']") 
WebElement clickOnAdmin;

public WebElement adminClick() {
    return clickOnAdmin;
}

Upvotes: 2

Views: 140

Answers (4)

S K
S K

Reputation: 335

I would suggest trying writing your XPATH as //span[contains(@class,'left-menu-title') and .='Admin']

And instead of just element.click(); use javascript executor click. Like how it's below:

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", driver.findElement(By.xpath("//span[contains(@class,'left-menu-title') and .='Admin']")));

Hope this works for you! Let me know.

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193058

As per the HTML you have shared, the following code block must work :

@FindBy(xpath = "//span[@class='left-menu-title selectorgadget_selected' and contains(.,'Admin')]") 
WebElement clickOnAdmin;

public WebElement adminClick() {
    clickOnAdmin.click();
}

Note : As you named the function as adminClick(), assuming you want to invoke click() method on the WebElement clickOnAdmin, click() method won't return anything. hence you have to discard the return clickOnAdmin; statement as well.

Upvotes: 0

alecxe
alecxe

Reputation: 473803

There are multiple classes but you are checking left-menu-title only.

The case of a SPAN tag name may also be a problem depending on a driver.

Fixed version, using contains() (note that it is not an ideal class XPath check - you need the concat and normalize-space, strictly speaking):

//span[contains(@class, 'left-menu-title')][text()='Admin']

Upvotes: 4

Ya Yan
Ya Yan

Reputation: 63

what @alecxe wrote is a very good pointer.

Usually when a website has a strong front-end code embedded with data+JS, you should use functionalities. Especially when absolute xpath does not work such as your case with data var on the front-end. "data-xpal="xpath-verify-selected"

Guru99 xpath fonctionalities

  1. also please verify if your application or website is not embedded with iFrames. if so please change iframe window.

  2. if you can provide the stackTrace Error. I assume you are talking about NullPointerException or NotFindElementException.

Upvotes: 0

Related Questions