python - 使用 BeautifulSoup4 完成后,如何进一步过滤汤对象?
问题描述
我正在尝试学习如何解析 HTML 数据,所以我选择了这个网站 ( http://ets.aeso.ca/ets_web/ip/Market/Reports/CSMPriceReportServlet ),它有电价的实时数据。
from bs4 import BeautifulSoup
from urllib.request import urlopen
import pandas as pd
url = "http://ets.aeso.ca/ets_web/ip/Market/Reports/CSMPriceReportServlet"
page = urlopen(url)
html = page.read().decode("utf-8")
soup = BeautifulSoup(html, "html.parser")
print(soup.get_text())
我的问题是如何在创建 BS4 对象后进一步解析/过滤它?
我只想要更新的数据,以便我可以将其放入熊猫数据框中。
像这样:
日期(他)| 时间|价格($)| 体积(兆瓦)
2021 年 1 月 15 日| 14 |13:10 |40.16| 80
2021 年 1 月 15 日| 14 |13:05 |40.18| 100
2021 年 1 月 15 日 | 14 |13:00| 40.16| 80
解决方案
正如goalie1998 所说,最简单的方法是使用pandas
,只需两行代码。
例子
请注意,pandasread_html()
将所有表存储在数据框列表中。因为您想要的表是源中的第三个表,您可以通过切片数据框列表直接选择它[2]
import pandas as pd
pd.read_html('http://ets.aeso.ca/ets_web/ip/Market/Reports/CSMPriceReportServlet')[2]
输出
Date (HE) Time Price ($) Volume (MW)
0 01/15/2021 14 13:10 40.16 80
1 01/15/2021 14 13:05 40.18 100
2 01/15/2021 14 13:00 40.16 80
3 01/15/2021 13 12:40 40.16 80
4 01/15/2021 13 12:00 40.01 100
5 01/15/2021 12 11:54 40.01 100
6 01/15/2021 12 11:00 40.18 100
7 01/15/2021 11 10:54 40.18 100
8 01/15/2021 11 10:24 40.16 80
9 01/15/2021 11 10:00 40.18 100
以防万一你真的不得不去beautifulsoup
- 在网站上选择第三个
table
或table
没有课程 - 选择所有的
tr
并table
循环它们并附加td
数据列表中的所有文本 - 将数据列表导入到
pandas
例子
from bs4 import BeautifulSoup
from urllib.request import urlopen
import pandas as pd
url = "http://ets.aeso.ca/ets_web/ip/Market/Reports/CSMPriceReportServlet"
page = urlopen(url)
html = page.read().decode("utf-8")
soup = BeautifulSoup(html, "html.parser")
data = []
rows = soup.select('table:not([class]) tr')
for i,row in enumerate(rows):
if i == 0:
cols = row.find_all('th')
else:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele])
pd.DataFrame(data[1:], columns=data[0])
推荐阅读
- python - Keras 导入错误:没有名为“google”的模块,Jupyter Notebook Anaconda
- angular - 如何在使用 ngx-charts 库构建的饼图中显示数据标签?
- typescript - 为什么数字枚举可以分配给打字稿中的任何数字?
- php - 请求输入 laravel ajax 在更新方法上返回 null
- angular - 如何将 Angular 版本从 7 升级到 8?
- python - 无法将多个图像保存为单个 pdf
- python-3.x - 如何将列表转换为str。'DataFrame' 对象不可调用错误
- drools - Drools 'and' 关键字是按位 & 吗?
- jquery - 如何从同一类中获取价值
- mysql - 如何仅获取当前年份?