【问题标题】:Parsing one table out of several tables contained in a html page using python使用python从html页面中包含的多个表中解析一个表
【发布时间】:2020-06-10 05:40:07
【问题描述】:

我正在尝试在this link 的 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 代码here。

【问题讨论】:

  • 你是怎么登录的?
  • 您感兴趣的页面要求提供登录凭据
  • @KarthickMohanraj 和 Datanovice 都道歉,我已将 html 代码复制并粘贴到 codepen 中

标签: python pandas html-table html-parsing


【解决方案1】:

所以,我编辑了@KarthickMohanraj 提供的代码,以实现第一步,即读取本地保存的html 文件。最终代码如下:

from bs4 import BeautifulSoup
import pandas as pd

# opens html file saved locally
filepath = 'Aluminium_Profiles_profiles.html'
f = open(filepath, 'r', encoding='utf8', errors='ignore')

# reads html code as string
s = f.read()

# parse html string with BeautifulSoup
soup = BeautifulSoup(s) #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_df = pd.read_html(extracted_table_html)[0]

【讨论】:

    【解决方案2】:

    我已将您提供的 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 行以保持答案简短)

    【讨论】:

    • 太棒了,谢谢!我将如何修改代码以读取 <a href> 标签并将其输入到下载 EPD 字段/列中?
    猜你喜欢
    • 2014-07-05
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2015-06-08
    相关资源
    最近更新 更多