简体   繁体   中英

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;

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']

Here are different options.

Option 1:

//table[@id='subtotals-marketplace-table']//tr[td[normalize-space(.)='Total:']]/td[2]

Option 2:

//table[@id='subtotals-marketplace-table']//td[normalize-space(.)='Total:']/following-sibling::td

To locate the text Total and then extract the amount associated with $ you can use the following solution:

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

Update

As you are seeing the error as Unable to locate an element with the xpath expression , possibly you have to induce WebDriverWait for the element to be clickable and you can use the following solution:

new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.TextToBePresentInElementLocated(By.XPath("//table[@id='subtotals-marketplace-table']/tbody//td/span[contains(.,'Total:')]/following::td[1]"), "$")).GetAttribute("innerHTML");

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