1

So basically what I need help in is:

I want to search for BBXXCODE with selenium-3.141.0, and Python 3.8.5. I'm using driver.find_element_by_xpath("//*[contains(text(),'BBXXCODE')]" which is working as expected. But I need to somehow extract the id of the <tr> tag on top, because I want to use driver.find_element_by_xpath('//*[@id="tr9"]/td[2]/h1').click() to click on the I need to select this text.

Is there a way to do this or should I stay searching via the I need to select this text instead of the code?

This is the code piece:

<tr id='tr9'>
    <td></td>
    <td role='gridcell'>
        <span class='link'>I need to select this</span>
    </td>
    <td role='gridcell'>
        BBXXCODE
    </td>
</tr>

I hope it is mostly clear, if not, feel free to tell me I'll try to add more details to it. Thanks in advance

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352

2 Answers2

1

To extract the id of the <tr> tag with respect to the text BBXXCODE you can use either of the following Locator Strategies:

  • Using xpath and parent:

    tr_id = driver.find_element_by_xpath("//td[contains(., 'BBXXCODE')]//parent::tr[1]").get_attribute("id")
    
  • Using xpath and ancestor:

    tr_id = driver.find_element_by_xpath("//td[contains(., 'BBXXCODE')]//ancestor::tr[1]").get_attribute("id")
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • This is working perfectly, but as JeffC mentioned that answer is one step, no need anything else, than a .click(). – Skeleton022 Sep 22 '20 at 22:00
1

Rather than get the ID and then find the other element (in two steps), I would suggest, if possible, that you just get it in one step. You can use the XPath below to find the desired SPAN based on the location of the BBXXCODE.

//tr[./td[contains(text(),'BBXXCODE')]]/td/span
JeffC
  • 22,180
  • 5
  • 32
  • 55
  • For my specific case this is the fastes and easiest to do. I can use it with the click function and get the result within one step. – Skeleton022 Sep 22 '20 at 21:58