python - 如何使用 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')
解决方案
正如@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
推荐阅读
- azure - Microsoft Azure 流分析和 Blob 存储输入
- c++ - 从 Arduino SD 卡模块到 Array 的文件名
- python - Python 脚本“独立”
- java - Runge-Kutta 4 阶与 2 阶 ODE 错误
- vb.net - 寻求解决无限循环
- javascript - 如何在 Laravel 上使用 webpack 和 Datatable
- swift - 如何使用 alamofire 快速处理韩语编码?
- html - MS 边缘图形异常
- r - 在数据框中使用 R 检索带有财务数据的 jsonfile
- python - 使用 Python 和 Graph API 发布到 Facebook,权限问题