【问题标题】:Python scraping stock pricesPython 抓取股价
【发布时间】:2015-12-01 12:12:50
【问题描述】:

我最近看到一个帖子,说有人在雅虎财经页面上抓取股票价格,代码是这样的:

from bs4 import BeautifulSoup
import requests


name = input('>')
url = 'http://finance.yahoo.com/q?s={}'.format(name)
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
data = soup.find('span', attrs= {'id':'yui_3_9_1_8_1448922823083_37'.format(name)})
print(data.text)

我认为代码本身可能有效,但只有 ID 是错误的,因为它说:

'NoneType' object has no attribute 'text'

我要问的是如何为价格找到正确的 HTML 标签(例如google(goog))。

如果有人有时间,我也想知道如何在更改 div id 的同时抓取多个股票(在 name=input('>) 上放置一个 while 循环,直到我说“停止”) ,我不知道我该怎么做。

【问题讨论】:

    标签: python python-3.x input beautifulsoup


    【解决方案1】:

    自编写代码以来,正在搜索的 ID 已更改。以下应该可以工作,它还向您展示了在输入end 之前如何保持循环:

    from bs4 import BeautifulSoup
    import requests
    import re
    
    while True:
        symbol = input("Enter symbol: ")
    
        if symbol == 'stop':
            break
    
        url = 'http://finance.yahoo.com/q?s={}'.format(symbol)
        r = requests.get(url)
        soup = BeautifulSoup(r.text, "html.parser")
    
        try:
            data = soup.find('span', attrs= {'id' : re.compile(r'yfs_.*?_{}'.format(symbol.lower()))})
            print('{} = {}'.format(symbol, data.text))
        except AttributeError:
            print("Unknown symbol: {}".format(symbol))
    

    这将为您提供以下输出:

    Enter symbol: GOOG
    GOOG = 742.60
    Enter symbol: EURGBP
    EURGBP = 0.7040
    Enter symbol: stop
    

    【讨论】:

    • 嗨马丁斯,我收到一条错误消息,上面写着“未定义名称're'”,所以我认为您的意思是 r.compile,但是,我在执行此操作时收到了另一条错误消息: “响应”对象没有属性“编译”
    • 我已经更新了脚本,只需在顶部添加import re
    • 我也有一个(可能是愚蠢的问题),但是假设我去另一个页面显示股票信息,我如何(在 html 代码中)找到价格所在的位置?在这种情况下,它在 yfs 中,但我怎么才能找到它呢? @马丁埃文斯
    • 使用普通浏览器访问该站点并查找所需的库存。然后使用view source 并使用find 搜索相同的股票值。
    猜你喜欢
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2021-03-04
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多