【问题标题】:extract yahoo finance balance sheet with python用python提取雅虎财务资产负债表
【发布时间】:2015-09-25 15:52:00
【问题描述】:

我正在学习使用 beautifulsoup 和 python 来提取 html 表格。我尝试使用以下代码为 Google 提取资产负债表。但是,我似乎无法正确抓取所有行。

我无法省略只是一个分隔符的行,也无法提取总计的行(例如,总资产)。

有什么建议吗?关于简化代码的建议也很有价值。

from bs4 import BeautifulSoup
import requests

def bs_extract(stock_ticker):
    url= 'https://finance.yahoo.com/q/bs?s='+str(stock_ticker)+'&annual'
    source_code = requests.get(url)
    plain_text=source_code.text
    soup = BeautifulSoup(plain_text)

    c1= ""
    c2= ""
    c3= ""
    c4= ""
    c5= ""

    table = soup.find("table", { "class" : "yfnc_tabledata1" })
    # print (table)
    for row in table.findAll("tr"):
        cells = row.findAll("td")
        if len(cells)==5:
            c1=cells[0].find(text=True)
            c2=cells[1].find(text=True)
            c3=cells[2].find(text=True)
            c4=cells[3].find(text=True)
            c5=cells[4].find(text=True)
        elif len(cells)==6:
            c1=cells[1].find(text=True)
            c2=cells[2].find(text=True)
            c3=cells[3].find(text=True)
            c4=cells[4].find(text=True)
            c5=cells[5].find(text=True)
        elif len(cells)==1:
            c1=cells[0].find(text=True)
            c2=""
            c3=""
            c4=""
            c5=""
        else:
            pass
        print(c1,c2,c3,c4,c5)

 bs_extract('goog')

【问题讨论】:

  • goog 的网页没有包含 yfnc_tabledata1 类的表格
  • Google 和 Yahoo 将以非常不同的方式显示他们的表格。 yfnc 可能是“雅虎财经”的缩写。为什么 Google 会使用他们的 ID 和标签?打开浏览器的开发者工具并尝试检查元素以了解如何在您想要的页面上进行解析。
  • 关于使它更加 Pythonic 的说明:您可以将这些变量(c1、c2 等)放入一个列表中,而不是单独的变量,这样您就不必有那么多重复的代码.

标签: python beautifulsoup yahoo-finance


【解决方案1】:

您可能会发现通过 YQL 更容易结构化这些数据。见http://goo.gl/qKeWXw

【讨论】:

  • 只是为了回应库皮亚科斯。我尝试使用 bs_extract('msft') ,您会在源代码的某处找到 yfnc。清单上的好点。知道为什么我不能以粗体提取行(即总计)吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多