如何在Selenium WebDriver中使用文本获取标记的索引/位置?

时间:2015-03-05 11:40:27

标签: selenium selenium-webdriver

例如,考虑以下html标记,我需要获取文本的确切索引/位置three

<tr>
 <td>one</td>
 <td>two</td>
 <td>three</td>
</tr>

预期值为 3 &#39;

2 个答案:

答案 0 :(得分:4)

以下是使用 JAVA

的相同示例
driver.get("http://www.indiabookstore.net/");

WebElement list = driver.findElement(By.xpath("//ul[@class='nav navbar-nav navbar-right']"));        
WebElement li = list.findElement(By.xpath("*[. = 'Offers']"));        
List<WebElement> children = driver.findElements(By.tagName("li"));        
System.out.println(children.indexOf(li));

答案 1 :(得分:3)

你可以这样做:

from selenium import webdriver

driver = webdriver.Firefox()

# This is an actual bin with a test page in it.
driver.get("http://jsbin.com/wagonazipa")

# Obviously, this needs to be precise enough to find the tr 
# you care about. Adapt as needed.
tr = driver.find_element_by_tag_name("tr")

# Find the element you care about. You might want to use td rather 
# than *.    
target = tr.find_element_by_xpath("*[. = 'three']")

# Get all the children of the row.
children = tr.find_elements_by_xpath("*")

# Get the index of target in the children list.
print children.index(target)

Python的Selenium实现是这样的,您可以对WebElement==对象进行比较,从而index起作用。如果您使用的语言不能执行此操作,则必须获取Selenium分配给每个WebElement对象的标识符。在Python上,.id属性。在其他语言中,您可以使用getId()get_id()方法来获取ID。然后,您可以按标识符比较WebElement个对象。

如果jsbin无法访问,则这是其中的相关HTML:

<body>
  <table>
    <tr>
      <td>one</td>
      <td>two</td>
      <td>three</td>
    </tr>
  </table>
</body>