我最近開始瞭解更多關於Python的知識以及如何使用BeautifulSoup解析網站。從BeautifulSoup解析獲取特定值
我現在面臨的問題是我似乎被卡住了。
HTML代碼(後作出的湯):
<div class="mod-3-piece-app__visual-container__chart">
<div class="mod-ui-chart--dynamic" data-chart-config='{"chartData":{"periods":[{"year":2013,"period":null,"periodicity":"A","icon":null},{"year":2014,"period":null,"periodicity":"A","icon":null},{"year":2015,"period":null,"periodicity":"A","icon":null},{"year":2016,"period":null,"periodicity":"A","icon":null},{"year":2017,"period":null,"periodicity":"A","icon":null},{"year":2018,"period":null,"periodicity":"A","icon":null}],"forecastRange":{"from":3.5,"to":5.5},"actualValues":[5.6785,6.45,9.22,8.31,null,null],"consensusData":[{"y":5.6307,"toolTipData":{"low":5.5742,"high":5.7142,"analysts":34,"restatement":null}},{"y":6.3434,"toolTipData":{"low":6.25,"high":6.5714,"analysts":35,"restatement":null}},{"y":9.1265,"toolTipData":{"low":9.02,"high":9.28,"analysts":40,"restatement":null}},{"y":8.2734,"toolTipData":{"low":8.17,"high":8.335,"analysts":40,"restatement":null}},{"y":8.9304,"toolTipData":{"low":8.53,"high":9.63,"analysts":41,"restatement":null}},{"y":10.1252,"toolTipData":{"low":8.63,"high":11.61,"analysts":42,"restatement":null}}]}}'>
<noscript>
<div class="mod-ui-chart--static">
<div class="mod-ui-chart--sprited" style="width:410px; height:135px; background:url('/data/Charts/EquityForecast?issueID=36276&height=135&width=410') 0px -270px no-repeat;">
</div>
</div>
</noscript>
</div>
</div>
我的代碼:
from bs4 import BeautifulSoup
import urllib.request
data = []
List = ['AAPL']
# Iterates Through List
for i in List :
# The webpage which we wish to Parse
soup = BeautifulSoup(urllib.request.urlopen('https://markets.ft.com/data/equities/tearsheet/forecasts?s=AAPL:NSQ').read(), 'lxml')
# Gathering the data
Values = soup.find_all("div", {"class":"mod-3-piece-app__visual-container__chart"})[4]
print(Values)
# Getting desired values from data
我希望獲得的是價值後{"y" ....,
因此數字5.6307,6.3434,9.1265, 8.2734, 8.9304 and 10.1252
,但我不能爲我的生活想出瞭如何。我試過Values.get_text
以及Values.text
,但這只是空白(可能是因爲所有的代碼都在列表或類似內容中)。
如果我可以在「toolTipData」之後得到數據,那也可以。
有沒有人介意幫助我?
如果我錯過了任何內容,請提供反饋意見,以便我將來可以提出更好的問題。
謝謝
謝謝你改變了
'actualValues'
,這當我嘗試將其他資產(IBM爲例)val1-完全適用於1資產情況(僅AAPL),但val4得到過分誇大。我會盡我所能找到一種方法將這本詞典拆分成一個列表,然後在每次運行時追加它。 –