【问题标题】:How to download html table content?如何下载html表格内容?
【发布时间】:2019-12-18 07:54:35
【问题描述】:

我想从以下网站下载财务数据(“konsernregnskap”而不是“morregnskap”),但我不知道如何下载所有内容:https://www.proff.no/regnskap/yara-international-asa/oslo/hovedkontortjenester/IGB6AV410NZ/

尝试使用 xpath 定位表,但没有成功。

我想将所有内容下载到一张 Excel 表格中。

【问题讨论】:

  • 您需要检查//div[@id="keyFigures_corporateAccounts"] 以获得您需要的数据。
  • 寻求调试帮助时请附上您的代码

标签: python web-scraping beautifulsoup scrapy


【解决方案1】:

您在类 table-wrap 中有 8 个表,前 4 个表属于“morregnskap”选项卡,接下来的 4 个表属于“konsernregnskap”选项卡,因此通过选择最后 4 个表,您可以从中选择所需的表开始抓取您的数据

import requests
import json
import bs4

url = 'https://www.proff.no/regnskap/yara-international-asa/oslo/hovedkontortjenester/IGB6AV410NZ/'


response = requests.get(url)
soup = bs4.BeautifulSoup(response.text, 'lxml')
tables = soup.find_all('div', {'table-wrap'})


konsernregnskap_data = tables[5:]

【讨论】:

    【解决方案2】:

    @rusu_ro1 给出的答案是正确的。但是,我认为Pandas 是在这里工作的正确工具。

    您可以使用pandas.read_html 获取页面中的所有表格。然后使用 pandas.DataFrame.to_excel 仅将最后 4 个表写入 excel 工作簿。

    以下脚本会抓取数据并将每个表写入不同的工作表。

    import pandas as pd
    all_tables = pd.read_html(
        "https://www.proff.no/regnskap/yara-international-asa/oslo/hovedkontortjenester/IGB6AV410NZ/"
    )
    with pd.ExcelWriter('output.xlsx') as writer:
        # Last 4 tables has the 'konsernregnskap' data
        for idx, df in enumerate(all_tables[4:8]):
            # Remove last column (empty)
            df = df.drop(df.columns[-1], axis=1)
            df.to_excel(writer, "Table {}".format(idx))
    

    注意事项:

    flavor : str 或 None,字符串容器

    要使用的解析引擎。 ‘bs4’ 和 ‘html5lib’ 是同义词 彼此,它们都是为了向后兼容而存在的。这 默认为 None 尝试使用 lxml 进行解析,如果失败则失败 回到 bs4 + html5lib。

    来自HTML Table Parsing Gotchas

    html5lib 从无效标记生成有效的 HTML5 标记 自动地。这对于解析 HTML 表格非常重要, 因为它保证了一个有效的文件。然而,这并不意味着 这是“正确的”,因为修复标记的过程没有 单一定义。

    在您的特定情况下,它会删除第 5 个表(仅返回 7 个)。也许 b'coz 第 1 表和第 5 表的数据相同。

    【讨论】:

      猜你喜欢
      • 2015-12-04
      • 1970-01-01
      • 2014-04-08
      • 2018-05-17
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      相关资源
      最近更新 更多