Search code examples
pythonseleniumselenium-webdriverxpathxpath-1.0

How to extract the value from the <td> element within the table using Selenium and Python


I'm trying to extract the value 1 from the table with Selenium, but I'm not finding a good way to do it.

<td width="1%" style="text-align: right">1</td>

Here is how the page's HTML looks like:

<tr class="linhaPar" onMouseOver="javascript:this.style.backgroundColor='#C4D2EB'" onMouseOut="javascript:this.style.backgroundColor=''">
   <td>
      Scientific American
   </td>
   <td>
      A Base Molecular da Vida  Uma Introducao a Biologia Molecular
   </td>
   <td>
   </td>
   <td>
      <table width="100%">
         <tbody style="background-color: transparent;">
            <tr>
               <td>
                  1971
               </td>
            </tr>
         </tbody>
      </table>
   </td>
   <td width="1%" style="text-align: right">
      1
   </td>
   <td width="1%">	
      <a id="formBuscaPublica:ClinkView" href="#" onclick="if(typeof jsfcljs == 'function'){jsfcljs(document.getElementById('formBuscaPublica'),{'formBuscaPublica:ClinkView':'formBuscaPublica:ClinkView','idTitulo':'39117','idsBibliotecasAcervoPublicoFormatados':'47_46','apenasSituacaoVisivelUsuarioFinal':'true'},'');}return false"><img id="formBuscaPublica:ImageView" src="/sigaa/img/view.gif" style="border:none" title="Visualizar Informa&ccedil;&otilde;es dos Materiais Informacionais" /></a>
   </td>

I've tried using this code, but it didn't work at all.

x = browser.find_elements_by_xpath('//*[@id="listagem"]/tbody/tr[1]/td[5]/').text

Thanks!


Solution

  • Try following xpath:

    x = driver.find_element_by_xpath('//tr[@class="linhaPar" and contains(.,"Scientific American")]//td[contains(@style, "text-align")]').text
    print(x)
    

    Note:

    Don't use .find_elements, but .find_element