【问题标题】:Python splice dataPython拼接数据
【发布时间】:2020-07-21 03:40:54
【问题描述】:

我已拆分数据,但 daychange = price.split('(', 1)[1].split('%')[0] 当前显示 +0.84,但我正在努力寻找将 0.84 与 + 分开的最佳方法(因为它也可能是 -)。

import requests
from bs4 import BeautifulSoup

url = 'https://finance.yahoo.com/quote/%5EGSPC?p='
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
price = soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'})[0].find_all('span')[1].text
daychange = price.split('(', 1)[1].split('%')[0]
#plusminus = price.split('(', 1)[1].split(')')[0].find('+')
print(daychange)

我相信这很简单。任何帮助都会很棒。

【问题讨论】:

    标签: python-3.x beautifulsoup split


    【解决方案1】:

    在 Yahoo!Finance 中,您可以使用正变量 +0.0070(+1.20%)、负变量 -0.24(-0.92%) 或无变量 0.00(0.00%)。要包含所有三种情况,您可以测试字符串的第一个字符,如果不为零,您可以使用剩余的字符串 (daychange[1:])。

    ...
    ...
    daychange = price.split('(', 1)[1].split('%')[0]
    print(daychange)
    
    if daychange[0] != "0":
        plusminus = daychange[0]
        abs_daychange = float(daychange[1:])
    else:
        plusminus = ""  # no sign
        abs_daychange = float(daychange)
    
    print((plusminus, abs_daychange))
    #('-', 0.62)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 2013-02-13
      • 1970-01-01
      • 2010-12-24
      • 1970-01-01
      • 2011-03-19
      相关资源
      最近更新 更多