python - 如何存储解析后的html结果?

标签 python url html-parsing beautifulsoup finance

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

事情并不美好。这是代码

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) 部分,我会很高兴。我还不明白类。

最佳答案

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

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. 连接节点中的元素,因此它是1个元素,而不是长度为1个元素的列表''.join()(Python技巧)

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

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

关于python - 如何存储解析后的html结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11814224/

相关文章:

python - pyqt GUI编程中如何组织类

python - 将 Iris 约束与 OR 结合起来?

angular - Firebase 存储 : Invalid argument count in `getDownloadURL` : Expected 0 arguments, 收到 1

python - 在 Python 中从 HTML 中提取链接

perl - 提高 LWP::Simple perl 性能

python - 如何取消列出 pandas 列中具有一个值的列表?

python - Django 分析

url - KeyCloak 忘记密码 电子邮件链接

c# - Amazon S3 - 如何正确构建指向存储桶中对象的 URL?

php - 如何输出精确的字符串 "<?php"