Home > Blockchain >  Using text from cell to match title to obtain cell below with Python and Selenium
Using text from cell to match title to obtain cell below with Python and Selenium

Time:02-03

I am trying to fetch the text of a cell from a table where the title matches "Make" in the another cell in the same table row.

For example, in the code example below I am trying to fetch the text "Lako" from the <a> within a <td> (cell) and it needs to match the title "Make" in the <td> (cell) above within the same <tr>(row). Unfortunately, all other tables have the same layout

I have tried the following, but it did not work:

driver.find_element_by_xpath('//tr[contains(text(), "Make")]/td[@]/a')

Example code:

<tbody><tr>
    <td >Website ref. :</td>
    <td >7334892</td>
</tr><tr>
    <td >Bodywork</td>
    <td ><a title="used car carrier semi-trailer" href="/car-carrier-semi-trailer/1-35-v88/used-car-carrier-semi-trailer.html" onclick="gtag('event', 'click', {'event_category': 'technicalSheet', 'event_label': 'listing-var', 'value': ''});"> Car carrier </a>
    </td>
</tr><tr>
    <td >Make</td>
    <td ><a href="/lako-car-carrier-semi-trailer/~a1b35c88e2161/lako-car-carrier.html" title="Lako car carrier semi-trailer" onclick="gtag('event', 'click', {'event_category': 'technicalSheet', 'event_label': 'listing-brd', 'value': ''});"><span>Lako</span></a></td>
</tr><tr>
        <td >Model</td>
        <td >DUPLO PISO</td>
    </tr><tr>
    <td >Condition</td>
    <td >Used</td>
</tr><tr>
        <td >Date of first registration</td>
        <td >06/22/1994</td>
    </tr><tr>
    <td >Country</td>
    <td ><a title="used Lako semi-trailer PORTUGAL" href="/lako-semi-trailer/portugal/~a1b35e2161nPT/lako-portugal.html" onclick="gtag('event', 'click', {'event_category': 'technicalSheet', 'event_label': 'listing-country', 'value': '1'});">PORTUGAL</a></td>
</tr><tr>
    <td >Manufacturer</td>
    <td ><a title="used Lako" href="/used-lako/~a1e2161/ads.html" onclick="gtag('event', 'click', {'event_category': 'technicalSheet', 'event_label': 'listing-fam-brd', 'value': ''});">Lako</a></td>
</tr></tbody>

CodePudding user response:

Instead of an xpath, you can use driver.find_element_by_css_selector, anchoring your search on the parent tr of "Make":

driver.find_element_by_css_selector('tbody > tr:nth-of-type(3) a')

Should the tr with "Make" vary in position across pages, you can also use driver.execute_script to run a custom Javascript snippet:

result = driver.execute_script("""
  for (var i of document.querySelectorAll('tbody > tr')){
    if (i.querySelector('td.title').textContent === 'Make'){
       return i.querySelector('td.value a').textContent;
    }
  }
""")

CodePudding user response:

I used ancestor

driver.find_element_by_xpath('.//td[contains(text(),"Make")]//ancestor::tr/td[@]').text
  •  Tags:  
  • Related