简体   繁体   中英

Selenium WebDriver - How to find the index of line in table

I want to find the index of row in table(10 rows) by Selenium:

<table _ngcontent-c4="" class="table table-striped table-br" xpath="1">
<tr _ngcontent-c4="" plan-id="41220451" xpath="1">
<tr _ngcontent-c4="" plan-id="41220452" xpath="1">
<tr _ngcontent-c4="" plan-id="41220453" xpath="1">
<tr _ngcontent-c4="" plan-id="41220454" xpath="1">
<tr _ngcontent-c4="" plan-id="41220455" xpath="1">
<tr _ngcontent-c4="" plan-id="41220456" xpath="1">
<tr _ngcontent-c4="" plan-id="41220457" xpath="1">
<tr _ngcontent-c4="" plan-id="41220458" xpath="1">
<tr _ngcontent-c4="" plan-id="41220459" xpath="1">
<tr _ngcontent-c4="" plan-id="41220460" xpath="1">

The problem is to find the row with plan_id ="41220457" (index = 7)

I tried to use several locators, but no success.

Let find all table row as List

var table = chrome.FindElement(By.TagName("table"));
var tr = table.FindElements(By.TagName("tr"));

解决了这个问题: driver.FindElement(By.XPath("/html[1]/body[1]/sk-app[1]/sk-internal-template[1]/div[1]/div[3]/div[1]/jhi-plan[1]/div[2]/div[1]/div[1]/table[1]/tbody[1]/tr[contains(@plan-id, '" + plan_id + "')]/td[8]/div[1]/button[1]/span[1]")).Click();

You can simplify the code with this below.

driver.FindElement(By.XPath("//table[@xpath='1']//tr[contains(@plan-id, '" + plan_id + "')]/td[8]/div[1]/button[1]/span[1]")).Click();

If you have only one button in the column 8, you can further simplify the line as below.

driver.FindElement(By.XPath("//table[@xpath='1']//tr[contains(@plan-id, '" + plan_id + "')]/td[8]//button/span[1]")).Click();

Btw, if anyone want to get the index number as posted in the original query, then you can run the below javascript using driver instance.

document.evaluate("//table[@xpath='1']//tr[@plan-id='41220457']/preceding-sibling::tr", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength+1

Screenshot:

在此处输入图片说明 '

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