user20358
user20358

Reputation: 14736

How to loop thru elements in Selenium with C# using xpath using partial id

I have a bunch of divs. I am looping thru them using their class name: col-lg-3. In each of the divs by the class name above, I have xpaths like the ones below. I need to pick out the string value at td[4]

.//*[@id='item-186951']/div[1]/table/tbody/tr[6]/td[4]
.//*[@id='itemPNS18-152951']/div[1]/table/tbody/tr[6]/td[4]
.//*[@id='itemXYZ-8152951']/div[1]/table/tbody/tr[6]/td[4]
.//*[@id='item11641551']/div[1]/table/tbody/tr[6]/td[4]
.//*[@id='itemAPS12641']/div[1]/table/tbody/tr[6]/td[4]

This part is the one that is changing in every element [@id='{dynamically-changing-id}'], with the rest being constant. How do I loop over this? At the moment I am trying this but I only get the first item (understandably)

        //get all divs on page
        var elements = ...FindElements(By.ClassName("col-lg-3"));
        //for each div found
        foreach(var e in elements)
        {
            //get text at xpath
            string str = e.FindElement(By.XPath(".//*[@id='item-186951']/div[1]/table/tbody/tr[6]/td[4]"));
        }

Im using Selenium 2.53

Upvotes: 0

Views: 1322

Answers (1)

alecxe
alecxe

Reputation: 473773

You can check that id attribute starts with "item":

var elements = ThisPage.FindElements(By.XPath(".//*[starts-with(@id, 'item')]/div[1]/table/tbody/tr[6]/td[4]"))

Upvotes: 1

Related Questions