【问题标题】:import yahoo finance stock price with beautifulsoup and request使用beautifulsoup 导入yahoo Finance 股票价格和请求
【发布时间】:2018-01-02 10:11:16
【问题描述】:

所以我有一个检查股票价格的脚本。雅虎改变了一些东西,现在我得到的是百分比变化而不是股价。以下是原始脚本。当我运行它时,我得到“+0.70 (+0.03%)”,而不是 2,477.83。我真正看到的唯一区别是:

data-reactid="36"

data-reactid="35".

当我更改为 35 时,它失败了。 36 个作品,但仅显示 % 变化。我要的是股价,而不是百分比变化。

感谢您的帮助!

import urllib.request
from bs4 import BeautifulSoup


# S&P 500
page = urllib.request.urlopen("https://finance.yahoo.com/quote/%5EGSPC?p=^GSPC")
content = page.read().decode('utf-8')
soup = BeautifulSoup(content, 'html.parser')
valsp = soup.find("span", {"data-reactid": "36"}).decode_contents(formatter="html")
print(valsp)

【问题讨论】:

    标签: python beautifulsoup request stock


    【解决方案1】:

    属性 data-reactid = "35" 的 span 元素不止一个,因此请通过 class 属性选择您想要的。

    import urllib.request
    from bs4 import BeautifulSoup
    
    # S&P 500
    page = urllib.request.urlopen("https://finance.yahoo.com/quote/%5EGSPC?p=^GSPC")
    content = page.read().decode('utf-8')
    soup = BeautifulSoup(content, 'html.parser')
    # print (soup)
    valsp = soup.find("span", {"data-reactid": "35", "class" : "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"}).decode_contents(formatter="html")
    print(valsp)
    

    输出:

    2,477.83
    

    唯一的变化是代码中的这一行:

    valsp = soup.find("span", {"data-reactid":"35"}).decode_contents(formatter="html")
    

    valsp = soup.find("span", {"data-reactid": "35", "class" : "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"}).decode_contents(formatter="html")
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2020-07-08
    • 2021-12-20
    • 2021-12-12
    • 2017-01-08
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多