python-3.xweb-scrapingbeautifulsoup

How to find tr with multiple td contains particular text with beautifulsoup?


I need to find the <tr> data where multiple <td> contains particular text (10.13.18.150, StreaNetwork)

<tr id="fr119" onclick="fr_toggle(119)" ondblclick="document.location='firewall_rules_edit.php?id=120';" class="ui-sortable-handle" style="">
<td>
    <input type="checkbox" id="frc119" onclick="fr_toggle(119)" name="rule[]" value="120">
</td>

    <td title="traffic is passed">
    <a href="?if=lan&amp;act=toggle&amp;id=120" usepost="">
        <i class="fa fa-check text-success" title="click to toggle enabled/disabled status"></i>
    </a>
    <i class="fa fa-cog" title="advanced setting: gateway PeakJioAirtel " style="cursor: pointer;"></i>                     
    </td>
    <td> 
    10.13.18.150                                                    
    </td>
    <td> 
    StreaNetwork                                                
    </td>
</tr>

My Code:

from bs4 import BeautifulSoup
complete_soup = BeautifulSoup(html_data, 'html.parser')
complete_soup.find('tr:has(td:contains("StreaNetwork"))')

Is there any solution for this problem?


Solution

  • Try to adjust your find() to select() to use the css selectors and your script will grab the <tr>.

    In addition iterate the Resultset and print :nth-child(3), if the content is still in this element:

    complete_soup = BeautifulSoup(html_data, 'html.parser')
    for e in complete_soup.select('tr:has(td:contains("StreaNetwork"))'):
        print(e.select_one(':nth-child(3)').get_text(strip=True))
    

    or check against the ip:

    complete_soup = BeautifulSoup(html_data, 'html.parser')
    for e in complete_soup.select('tr:has(td:contains("StreaNetwork"))'):
        ip = e.select_one(':nth-child(3)').get_text(' ',strip=True)
        if '10.13.18.150' in ip:
            print(ip)