【问题标题】:How can I store the results of parsed html?如何存储解析的 html 的结果?
【发布时间】:2012-08-05 05:33:26
【问题描述】:

我正在使用 Python 的 HTMLParser 和 BeautifulSoup 来解析 Yahoo 财务数据。已经有一个非常好的包可以做到这一点,但它没有得到“有形价格/账面价值”,也就是说它在计算账面价值时包括商誉和其他无形资产。因此,我不得不推出自己的解决方案。

它并不漂亮。这是代码

from BeautifulSoup import BeautifulSoup
import urllib2
from HTMLParser import HTMLParse

class data(HTMLParser):
    def handle_data(self, data):
        print data
parser = data()

url='http://finance.yahoo.com/q/bs?s=BAC&annual'
response = urllib2.urlopen(url)
html = response.read()
soup=BeautifulSoup(html)
tangibles=[str(parser.feed(str(soup('strong')[24:26])))]

这有两个问题: 1)我依赖数据总是在雅虎页面的同一个地方,这不是最大的问题,但并不让我开心 和, 2) 真正的问题;

 tangibles=[str(parser.feed(str(soup('strong')[24:26])))]

是一个空列表,因为“数据”类只是打印我想要的东西而不是存储它。

如果您为我回答第 2 部分),我会很高兴。我还不懂课。

【问题讨论】:

    标签: python url html-parsing beautifulsoup finance


    【解决方案1】:

    摆脱数据和解析器并支持导入然后执行此操作。

    tangibles = [''.join(node(text=True)).strip() for node in soup('strong')[24:26]]
    

    我基本上将其更改为使用一些 python 列表理解。 Read more here if you are not aware of what list comprehension is in Python

    本质上它做了这些事情:

    1. 告诉soup 找到标记为strong 的元素并为每个实例命名node for node in soup.findAll('strong')[24:26]
    2. 在node 中,它会找到并完全删除强标签node.findAll(text=True) Beautiful soup docs about text=True
    3. 加入 node 中的元素,因此它的 1 个元素而不是长度为 1 个元素的列表 ''.join()(python 技巧)

      即['Net Stuff', '152,113,000'] vs [['Net Stuff'], ['152,113,000']]

    4. 删除多余的空格(尾随和前导).strip()

    【讨论】:

    • 好的,太棒了,这就行了;虽然[u'Net Tangible Assets', u'3,096,164  '] 我得到了这样的数据,你知道我怎样才能在值的末尾去掉 html 格式的东西吗?
    • .replace(' ', '') 所以[ ''.join(node.findAll(text=True)).strip().replace(' ', '') for node in soup.findAll('strong')[24:26] ] 现在变得有点丑了。 :)
    猜你喜欢
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多