BS4 获取 table 内的 TH 数据

BS4 get the TH data within the table

我正在尝试从具有如下 table 的网站读取数据:

<table border="0" width = "100%">
    <tr>
        <th width="33%">Product</th>
        <th width="34%">ID</th>
        <th width="33%">Serial</th>
    </tr>
    <tr>
        <td align='center'>
            <a target="_TOP" href="Link1.html">ProductName</a>
            <br>
            <a href='Link2.html' TARGET='_TOP'><img src='https://?uid=1'></a>
        </td>

        <td align='center'>
            <a target="_TOP" href="Link2.html">ProductID</a>
            <br>
            <a href='Link2.html' TARGET='_TOP'><img src='https://?uid=2'></a>
        </td>

        <td align='center'>
            <a target="_TOP" href="Link3.html">ProductSerial</a>
            <br>
            <a href='Link2.html' TARGET='_TOP'><img src='https://?uid=3'></a>
        </td>
    </tr>
</table>

我想要从这个 table 中得到的是标签内的 ProductID。

问题是,我正在尝试为此使用 BS4,找到 TAG,并读取其中的内容,但是如何准确地将 BS4 指向它?

我试过:

with open("src/file.html", 'r') as inf:
        html = inf.read()
        soup = bs4.BeautifulSoup(html, features="html.parser")
    for container in soup.find_all("table", {"td": ""}):
        print(container) 

但是不起作用..有什么办法可以实现吗?要阅读 a 标签内的内容?

您可以使用 :nth-of-type CSS 选择器:

print(soup.select_one("td:nth-of-type(2) a:nth-of-type(1)").text)

输出:

ProductID