首页 > 解决方案 > 如何使用 BeautifulSoup 在包含多个表的页面上选择一个表

问题描述

我想选择一个特定的表格(我在图像中标记了我想要获得的内容),但该页面有很多表格。如何选择我想要的表?

import requests
from bs4 import BeautifulSoup

URL = 'http://www2.bmf.com.br/pages/portal/bmfbovespa/lumis/lum-tipo-de-participante-ptBR.asp'
pagina = requests.get(URL)

soup = BeautifulSoup(pagina.content, 'html.parser')

tabelas = soup.findAll('table')

桌子

标签: pythonbeautifulsoup

解决方案


正如@match 所说,每个表格都作为唯一的标题。

这是一个完整的示例,它仅获取您在图像中标记的表格。

表格的标题是IBrX-50

import urllib.request as request
from bs4 import BeautifulSoup
from bs4.element import Tag
from typing import List


html = BeautifulSoup(
    request.urlopen(
        "http://www2.bmf.com.br/pages/portal/bmfbovespa/lumis/lum-tipo-de-participante-ptBR.asp"
    ).read().decode("ISO-8859-1"),
    "html.parser",
)

key = "IBrX-50"
tables: List[Tag] = html("table")
try:
    table = [
        *filter(lambda tbl: tbl.find("caption").text.strip() == key, tables)
    ][0]
    # do whatever when table is found
except IndexError:
    # do whatever when table not found
    pass

推荐阅读