首页 > 解决方案 > 使用python从html页面中包含的多个表中解析一个表

问题描述

我正在尝试在此链接上解析 html 页面内的表格,但我还没有找到一种方法来确保我可以指向正确的表格,因为该页面还包含一些其他表格 - 如附图所示。

我尝试了更简单的方法,使用 pandas.read_html 并让它弄清楚,但这只会返回页面顶部的内容(我猜),错过了其他所有内容。

import pandas as pd
url='https://www.360optimi.com/app/sec/resourceType/benchmarkGraph?resourceSubTypeId=5c9316b28e202b46c92ca518&resourceId=envdecAluminumWindowProfAl&profileId=Saray2016&benchmarkToShow=co2_cml&entityId=5e4eae0f619e783ceb5d0732&indicatorId=lcaForLevels-CO2&stateIdOfProject='
tables = pd.read_html(url)
print(tables[0])

返回:

            0         1         2
0     English  Français   Deutsch
1     Español     Suomi     Norsk
2  Nederlands   Svenska  Italiano

关于如何使用正确的 html 标签指向感兴趣的表的任何想法?

编辑:正如你们中的一些人指出,网页需要登录凭据(道歉),我在这里上传了 html 代码。

已检查代码的网页屏幕截图

标签: pythonpandashtml-tablehtml-parsing

解决方案


我已将您提供的 html 作为输入。如果您想在 url 上使用此代码,只需在使用此代码之前提取该 url 的 html

from bs4 import BeautifulSoup
import pandas as pd

Your_input_html_string = str(html_code_of_your_url)

soup = BeautifulSoup(Your_input_html_string) #Provide the html code of the url in string format as input over here

#The table id which you want to extract from this html is "resourceBenchmarkTable". So let's extract the html of this table alone from the entire html
extracted_table_html = str(soup.find_all("table",id="resourceBenchmarkTable"))

#Now, convert the specific extracted html of table into pandas dataframe
table_dataframe = pd.read_html(extracted_table_html)

print(table_dataframe)

输出:(仅显示前 5 行以保持答案简短)

在此处输入图像描述


推荐阅读