Search code examples
c#seleniumxpathgetattributexpath-1.0

C# Selenium XPath data from row that contains a span


I am trying to grab data from a table that has two columns. The rows do not have a distinct identifier. But I can search the first column for specifics to find out if I should grab the second column's data. There are multiple rows in the table although the example below I am just showing one row.

<table id="subtotals-marketplace-table" class="a-normal a-align-bottom a-spacing-none a-size-small">
<tbody><tr class="small-line-height">
<td>
    <span>
        Total:
    </span>
</td>
<td class="a-text-right aok-nowrap a-nowrap">
    $12.80
</td>
</tr>
</tbody></table>

I need to search for Total: and then grab the dollar amount in the next column. I've tried multiple iterations of something along these lines but can't seem to find the correct syntax:

driver.FindElement(
                    By.XPath(
                        "//*[@id='subtotals-marketplace-table']//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;

driver.FindElement(
                    By.XPath(
                        "//table[@id='subtotals-marketplace-table']//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;

driver.FindElement(
                    By.XPath(
                        "//table[@id='subtotals-marketplace-table']/tbody//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;

Solution

  • Try following Xpath.

    //table[@id='subtotals-marketplace-table']//tr//td[@class='a-text-right aok-nowrap a-nowrap']
    

    OR

    //table[@id='subtotals-marketplace-table']//tr//span[contains(.,'Total:')]/parent::td/following-sibling::td[@class='a-text-right aok-nowrap a-nowrap']