python - Beautiful Soup 获取 div 中第一个表的数据

标签 python beautifulsoup

我想从包含许多表的 div 中获取第一个表的数据,我该怎么做?

<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> 

我需要表 class="tblpor"的数据,下面是我创建的代码,但是它为我提供了 div 内所有表的数据。

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

请帮忙。

问候,babsdoc

最佳答案

您可以像这样使用 css 选择器选择第一个表。

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

从这里继续提取每行单元格中的数据非常简单。

关于python - Beautiful Soup 获取 div 中第一个表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45443709/

相关文章:

python - "in the root directory of the source tree"是什么意思?

python - pycurl 上的 DNS_SERVERS

python - Selenium +Python : Cannot get href

python - 如何在前端使用 django filter_horizo​​ntal?

python - 如何从Python播放视频片段?

Python Beautiful Soup 网络抓取 CNN 选举结果

python - 使用请求和 BeautifulSoup 在页面上找不到元素

python - python 和 CSV 中的 TypeError : a bytes-like object is required, 不是 'str'

python - 找出 BeautifulSoup4 使用的是哪个解析器?

python - 使用 BeautifulSoup 发布到页面以登录