简体   繁体   中英

How can Selenium in C# locate this span based on its value?

I have been trying various locators and can't find a simple solution to locating the number (which is dynamic and changing each page load) inside this span in C# Selenium. I am just trying to locate the span itself to start with.

<span inventory="Livecount">129</span>

I get the NoSuchElement exception, ie unable to locate element.

Last context-related thing: this span and its number live inside of a widget, which I have been able to locate just fine. That widget doesn't have a unique class or id, but a custom tag-name, so I'm only able to locate it reliably using the FindElement(By.TagName("inventorySearch")), which works. If there was a way I could use a CSS selector to start with that widget element (the parent) - and then chain down to the span inside it (there's only one span in each instance, so it would be easy to locate), that would solve it. My problem there is, I don't know how to indicate tagname inside a Seleniums CSS selector (ie classes and Id's have their . # symbols - is there a tagname equivalent in C# Selenium? Thanks.

Answering the question in the title, it is possible to locate a <span> with the text '129 via XPath :

//span[text()='129']

However I suspect that this number will change, so you may also want to consider locating the <span> where its inventory attribute equals 'Livecount' :

CSS Selector:

span[inventory='Livecount']

XPath:

//span[@inventory='Livecount']

Usage:

driver.FindElement(By.CssSelector("span[inventory='Livecount']"));
driver.FindElement(By.XPath("//span[@inventory='Livecount']"));

Paraphrasing your last question, you asked if it's possible to use a CSS selector with a custom tag-name. This is also possible.

Given the following HTML:

<inventorySearch>
    <span inventory="Livecount">129</span>
</inventorySearch>

To select the <span> within the <inventorySearch> element, use the following CSS selector:

inventorySearch > span

This is also possible using CSS

JQuery has a :contains pseudo selector

ie span:contains('129')

You will need to use the Selenium NuGet Support Package to get this functionality.

Install-Package Selenium.WebDriver.Extensions

This gives access to the Sizzle JQuery Selector Engine which provides the pseudo selector support.

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