0

I have a table of names and each of the names can be accessed by the following XPath: //*[@id="right_pane"]/div[1]/table/tbody/tr[INDEX]/td[2] where index is a number. What's the best way to search for these XPaths while using Selenium? My current solution is the following:

  1. Replace INDEX with 0
  2. Search for element
  3. Check if element is the correct one
  4. Increment INDEX and repeat

The process above seems inefficient as the starting index varies (I start at 0 but it's possible the first entry in the table starts at index 200) and searching for each element takes up to seconds (using an implicit wait until in selenium).

Is there a better approach to this problem? Or am I stuck searching 1 by 1?

user8114848
  • 173
  • 3
  • 10
  • Share HTML sample for the same – Andersson Oct 16 '17 at 16:32
  • I am sure there is a better approach but we can't really guess at what that might be. If you shared a link to the page or at least some of the relevant HTML we could give you an answer. – JeffC Oct 16 '17 at 17:15
  • Unfortunately I cannot share the page as it's set up locally only at the momemt – user8114848 Oct 16 '17 at 17:39
  • So your essentially waiting for an exception to be thrown and catching it when it fails to find each of the elements until the index exists? It would be better to use a general selector to return each row as a list of webelements, and then use those to iterate over... Or better yet, have a specific test case that is searching for something specific, instead of trying to test everything on the page (**too clever**). Then you could have a method that returns the webelement based on some text, or class, or value, etc... – mrfreester Oct 16 '17 at 17:46
  • Currently I implicitly waiting till I find the first element, then I don't implicitly wait for the rest till I find what I'm looking for. It's not ideal but it's the best that I've come up with. I can't test for a specific element unfortunately – user8114848 Oct 16 '17 at 17:59

1 Answers1

2

Instead of iterating explicitly over multiple values for INDEX,

//*[@id="right_pane"]/div[1]/table/tbody/tr[INDEX]/td[2]

replace INDEX with your test. For example, if you want the second td for the tr whose first td is "foo":

//*[@id="right_pane"]/div[1]/table/tbody/tr[td[1]="foo"]/td[2]
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • What does the `td[1]` bit equate to? I thought that it would be something more like `[.//td[1]='foo']` to indicate that it is a child of the `tr` given the relative reference, `.//`. – JeffC Oct 16 '17 at 17:19
  • `[td[1]='foo']` is all that's needed. `[./td[1]='foo']` would be redundant. And if you don't know the difference between `/` and `//`, see [**this**](https://stackoverflow.com/questions/35606708/what-is-the-difference-between-and-in-xpath). – kjhughes Oct 16 '17 at 18:50
  • So basically `./` is implied in the syntax `[td[1]="foo"]`. That's what I was looking for. Thanks – JeffC Oct 16 '17 at 19:21