babsdoc
babsdoc

Reputation: 749

Beautiful Soup Get data for first table in a div

I am trying to get the data for the first table from a div containing many tables, how do I do it?

<div class="mainCont port_hold ">
    <table class="tblpor">
        <tr><th>Company</th><th>Code</th></tr>
        <tr><td>ABC    </td><td>1234</td></tr>
        <tr><td>XYZ    </td><td>6789</td></tr>
    </table>

    <table class="tblpor MT25">
        <tr><th>Company</th><th>Industry</th></tr>
        <tr><td>ABCDEF </td><td>aaaaa   </td></tr>
        <tr><td>STUVWX </td><td>bbbbb   </td></tr>
    </table>
</div> 

I need the data for table class="tblpor" and following is the code I created, however it gives me the data for all the tables inside the div.

for x in soup2.find('table', class_='tblpor'):
    for y in soup2.findAll('tr'):
        for z in soup2.findAll('td'):
            print(z.text)

Please help.

Regards, babsdoc

Upvotes: 2

Views: 3431

Answers (1)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38932

You can select the first table using css selector like so.

first_table = soup.select_one("table:nth-of-type(1)")

Carrying on from here to extract data in the cells for each row is straightforward.

Upvotes: 8

Related Questions