BeautifulSoup 中股票的抓取变化价格
Scraping change price of stocks in BeautifulSoup
我正在尝试抓取一些股票的变动价格。
我试过这个:
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 使其正常工作,是否有任何解决方案可以使其同时适用于正色和负色而无需每次更改代码?
.
我试图删除 C($positiveColor)
但它给了我一个错误 AttributeError: 'NoneType' object has no attribute 'text'
.
我希望我的问题很清楚,如果有人能帮助我,我将不胜感激。
.
提前致谢
您可以在 list
到 select 中添加两个 classes
。
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)
我正在尝试抓取一些股票的变动价格。
我试过这个:
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 使其正常工作,是否有任何解决方案可以使其同时适用于正色和负色而无需每次更改代码?
.
我试图删除 C($positiveColor)
但它给了我一个错误 AttributeError: 'NoneType' object has no attribute 'text'
.
我希望我的问题很清楚,如果有人能帮助我,我将不胜感激。
.
提前致谢
您可以在 list
到 select 中添加两个 classes
。
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)