使用Python抓取雅虎财务资产负债表

时间:2016-07-27 05:36:12

标签: python regex web-scraping beautifulsoup python-requests

我的问题是向here提出问题的后续问题。

功能:

  

periodic_figure_values()

似乎工作正常,除非被搜索的订单项的名称出现两次。我所指的具体案例是试图获取“长期债务”的数据。上面链接中的函数将返回以下错误:

Traceback (most recent call last):
  File "test.py", line 31, in <module>
    LongTermDebt=(periodic_figure_values(soup, "Long Term Debt"))
  File "test.py", line 21, in periodic_figure_values
    value = int(str_value)
ValueError: invalid literal for int() with base 10: 'Short/Current Long Term Debt'

因为它似乎因“短期/当期长期债务”而被绊倒。你看,该页面既有“短期/现期长期债务”和“长期债务”。您可以使用Apple的资产负债表here查看源页面的示例。

我正试图找到一种方法让函数返回“长期债务”的数据,而不会在“短期/当期长期债务”上绊倒。

这是一个功能和一个例子,提取“现金和现金等价物”,工作正常,和“长期债务”,这是行不通的:

import requests, bs4, re

def periodic_figure_values(soup, yahoo_figure):
    values = []
    pattern = re.compile(yahoo_figure)
    title = soup.find("strong", text=pattern)    # works for the figures printed in bold
    if title:
        row = title.parent.parent
    else:
        title = soup.find("td", text=pattern)    # works for any other available figure
        if title:
            row = title.parent
        else:
            sys.exit("Invalid figure '" + yahoo_figure + "' passed.")
    cells = row.find_all("td")[1:]    # exclude the <td> with figure name
    for cell in cells:
        if cell.text.strip() != yahoo_figure:    # needed because some figures are indented
            str_value = cell.text.strip().replace(",", "").replace("(", "-").replace(")", "")
            if str_value == "-":
                str_value = 0
            value = int(str_value)
            values.append(value)
    return values

res = requests.get('https://ca.finance.yahoo.com/q/bs?s=AAPL')
res.raise_for_status
soup = bs4.BeautifulSoup(res.text, 'html.parser')
Cash=(periodic_figure_values(soup, "Cash And Cash Equivalents"))
print(Cash)
LongTermDebt=(periodic_figure_values(soup, "Long Term Debt"))
print(LongTermDebt)

2 个答案:

答案 0 :(得分:1)

最简单的方法是使用凸起的try/except使用 ValueError 组合:

import requests, bs4, re

def periodic_figure_values(soup, yahoo_figure):
    values = []
    pattern = re.compile(yahoo_figure)
    title = soup.find("strong", text=pattern)    # works for the figures printed in bold
    if title:
        row = title.parent.parent
    else:
        title = soup.find("td", text=pattern)    # works for any other available figure
        if title:
            row = title.parent
        else:
            sys.exit("Invalid figure '" + yahoo_figure + "' passed.")
    cells = row.find_all("td")[1:]    # exclude the <td> with figure name
    for cell in cells:
        if cell.text.strip() != yahoo_figure:    # needed because some figures are indented
            str_value = cell.text.strip().replace(",", "").replace("(", "-").replace(")", "")
            if str_value == "-":
                str_value = 0
### from here
            try:
                value = int(str_value)
                values.append(value)
            except ValueError:
                continue
### to here
    return values

res = requests.get('https://ca.finance.yahoo.com/q/bs?s=AAPL')
res.raise_for_status
soup = bs4.BeautifulSoup(res.text, 'html.parser')
Cash=(periodic_figure_values(soup, "Cash And Cash Equivalents"))
print(Cash)
LongTermDebt=(periodic_figure_values(soup, "Long Term Debt"))
print(LongTermDebt)

这个很好地打印出你的数字 请注意,在这种情况下,您并不真正需要re模块,因为您只检查文字(没有通配符,没有边界)等。

答案 1 :(得分:0)

您可以更改该函数,使其接受正则表达式而不是纯字符串。然后,您可以搜索^Long Term Debt以确保之前没有任何文字。您需要做的就是改变

if cell.text.strip() != yahoo_figure:

if not re.match(yahoo_figure, cell.text.strip()):