我正试图取消一些股票的变动价格。
我尝试过:
import requests
from bs4 import BeautifulSoup
url = requests.get('https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch').text
soup = BeautifulSoup(url, 'lxml')
ChangePrice = soup.find('span', {'class': 'Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($positiveColor)'}).text
print(ChangePrice)
输出:+1.59 (+0.36%)
。
您可以在ChangePrice
变量的末尾看到它是 $ positiveColor ,我的问题是当我放入亏损股票时,我必须将其更改为 $ negativeColor < / strong>使其正常工作,是否有任何解决方案可以使它们同时使用正色和负色,而无需每次都更改代码?
。
我尝试删除C($positiveColor)
,但它给我一个错误AttributeError: 'NoneType' object has no attribute 'text'
我希望我的问题很清楚,如果有人能帮助我,我将非常感激。
。
预先感谢
答案 0 :(得分:0)
您可以将两个classes
添加到list
中以选择其中一个。
import requests
from bs4 import BeautifulSoup
url = requests.get('https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch').text
soup = BeautifulSoup(url, 'lxml')
ChangePrice = soup.find('span', {'class': ['Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($positiveColor)',
'Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($negativeColor)']}).text
print(ChangePrice)