1

So I'm running into the issue where I need 90% of the time

//*[@id='MainContent']/tbody/tr[18]/td[2]

while I need 10% of the time

//*[@id='MainContent']/tbody/tr[20]/td[2]

I'm wondering what the best approach to compensate for this change would be.

Here are pictures of the table, and the html code to the table. enter image description here

enter image description here

I need to capture the 3 Bedrooms part, and there are times where the tr elements swap. Most of the time the first xpath code works, but I need a more efficient way of determining which xpath to use depending on the case at hand.

I know that a starts-with method exists for selenium, but would that allow me to search the actual TD text?

7
  • Can you inspect the text of the first xpath element, and use that to decide which element you need? i.e. something like if 'Bedrooms' in driver.find_element_by_xpath('//*[@id='MainContent']/tbody/tr[18]/td[2]') ? Commented Nov 4, 2018 at 1:54
  • I could do that, but I'm wondering if there is a method that already exists for selenium that would do just that, so instead of using an if statement, is there a method that searches for the text, and if the text is found can copy the xpath @JohnGordon Commented Nov 4, 2018 at 1:56
  • I don't understand what you're asking for. if 'something' in element.text: is about as direct as you can get. Commented Nov 4, 2018 at 2:31
  • @JohnGordon Does selenium not have a method that does this lookup directly? For instance, something like this: //*[text()[contains(.,'theText')]] Commented Nov 4, 2018 at 2:34
  • Oh, you mean an XPath selector. It's nothing specifically to do with Selenium. Commented Nov 4, 2018 at 2:36

2 Answers 2

3

To capture the text 3 Bedrooms with respect to the text Ttl Bedrms you can use the following solution:

  • XPath:

    //tr[@class='RowStyle']//td[contains(.,'Ttl Bedrms')]//following::td[1]
    
Sign up to request clarification or add additional context in comments.

1 Comment

Decided to use the text()= method because I am trying to match case exact text. In the event that they ever update the site, I can rely on the exact text matching and not just contains because there could be multiple places where that text may exist
2

How about using the Ttl Bedrms: text

//*[@id='MainContent']//td[contains(., `Ttl Bedrms:`)]/following-sibling::td

1 Comment

Thanks for your help. I used something similar to this, but I used the text()= method instead of contains(x,x)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.