【问题标题】:For Loop only prints the first valueFor Loop 只打印第一个值
【发布时间】:2021-08-11 17:55:00
【问题描述】:

我正在尝试使用 for 循环在五只股票的列表上从网络上抓取股票数据。问题是只有第一个值被返回五次。我试过附加到一个列表,但它仍然不起作用,虽然很明显我没有正确附加。在网站上,我想获取运营现金的数据,例如以 14B 或 1B 的形式出现,这就是为什么我删除了 B 并将该数字相乘以获得原始值的原因。这是我的代码:

import requests
import yfinance as yf
import pandas as pd
from bs4 import BeautifulSoup
headers = {'User Agent':'Mozilla/5.0'}
stocks = ['AMC','AMD','PFE','AAPL', 'NVDA']
finished_list = []
for stock in stocks:
    url = f'https://www.marketwatch.com/investing/stock/{stock}/financials/cash-flow'
    res = requests.get(url)
    soup = BeautifulSoup(res.content, 'lxml')
    operating_cash = soup.findAll('div', class_ = "cell__content")[134].text
    finished_list.append(operating_cash)
    if 'B' in operating_cash:
        cash1 = operating_cash.replace('B','')
        if '(' in cash1:
            cash2 = cash1.replace('(','-')
        if ')' in cash2:
            cash3 = cash2.replace(')','')
            cash3 = float(cash3)
            print(cash3*1000000000)
        else:
            cash1 = float(cash1)
            print(cash1 * 1000000000)

当前输出连续五次为 -1060000000.0,这是 AMC 运营现金的正确值,但对于其他四次则不正确。提前感谢任何可以帮助我的人。

【问题讨论】:

    标签: python for-loop


    【解决方案1】:

    您不需要为str.replace() 使用if 条件。相反,像这样在一行中完成所有替换:

    for stock in stocks:
        url = f'https://www.marketwatch.com/investing/stock/{stock}/financials/cash-flow'
        res = requests.get(url)
        soup = BeautifulSoup(res.content, 'lxml')
        operating_cash = soup.findAll('div', class_ = "cell__content")[134].text
        finished_list.append(operating_cash)
        cash = float(operating_cash.replace('B','').replace('(','-').replace(')',''))
        print(cash*1000000000)
    
    -1060000000.0
    1070000000.0000001
    14400000000.0
    80670000000.0
    5820000000.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多