【问题标题】:python beautifulsoup4 parsing google finance datapython beautifulsoup4解析谷歌财务数据
【发布时间】:2014-02-09 02:30:01
【问题描述】:

我不熟悉使用 beautifulsoup 和一般刮痧,所以可以这么说,我正试图弄湿我的脚。

我想从这里获取道琼斯工业平均指数的第一行信息: http://www.google.com/finance/historical?q=INDEXDJX%3A.DJI&ei=ZN_2UqD9NOTt6wHYrAE

虽然我可以读取数据并 print(soup) 输出所有内容,但我似乎还不够深入。我将如何选择保存到表中的行?第一行怎么样?

非常感谢您的帮助!

import urllib.parse
import urllib.request
from bs4 import BeautifulSoup
import json
import sys
import os
import time
import csv
import errno

DJIA_URL = "http://www.google.com/finance/historical?q=INDEXDJX%3A.DJI&ei=ZN_2UqD9NOTt6wHYrAE"

def downloadData(queryString):
    with urllib.request.urlopen(queryString) as url:
        encoding = url.headers.get_content_charset()
        result = url.read().decode(encoding)
    return result

raw_html = downloadData(DJIA_URL)
soup = BeautifulSoup(raw_html)

#print(soup)

table = soup.findAll("table", {"class":"gf-table historical_price"})

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    然后你想要第二个tr 表行:

    prices = soup.find('table', class_='historical_price')
    rows = prices.find_all('tr')
    print rows[1]
    

    或者,要列出所有包含价格信息的行,请跳过包含任何 th 元素的行:

    for row in rows:
        if row.th: continue
    

    或使用第一个标题作为字典键的来源:

    keys = [th.text.strip() for th in rows[0].find_all('th')]
    for row in rows[1:]:
        data = {key: td.text.strip() for key, td in zip(keys, row.find_all('td'))}
        print data
    

    产生:

    {u'Volume': u'105,782,495', u'High': u'15,798.51', u'Low': u'15,625.53', u'Date': u'Feb 7, 2014', u'Close': u'15,794.08', u'Open': u'15,630.64'}
    {u'Volume': u'106,979,691', u'High': u'15,632.09', u'Low': u'15,443.00', u'Date': u'Feb 6, 2014', u'Close': u'15,628.53', u'Open': u'15,443.83'}
    {u'Volume': u'105,125,894', u'High': u'15,478.21', u'Low': u'15,340.69', u'Date': u'Feb 5, 2014', u'Close': u'15,440.23', u'Open': u'15,443.00'}
    {u'Volume': u'124,106,548', u'High': u'15,481.85', u'Low': u'15,356.62', u'Date': u'Feb 4, 2014', u'Close': u'15,445.24', u'Open': u'15,372.93'}
    

    等等

    【讨论】:

    • 嗨,我应该什么时候使用 .find 以及什么时候使用 .find_all?
    • .find() 仅找到 第一个 匹配项或返回 None.find_all() 返回 0 个或多个匹配项的列表。
    • 太棒了。这真的很有帮助。 row.th 是不是 beautifulsoup 特有的?以前从未见过。
    • 是的。 BeautifulSoup 无法识别的任何属性都会转换为.find() 调用。 row.th 因此被翻译成row.find('th')
    猜你喜欢
    • 2019-04-27
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 2011-07-28
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多