下面的代碼不會失敗,但不完整。從這一點來看,我試圖只將所有完整游戲值放入資料幀中。
import json
from bs4 import BeautifulSoup
import urllib.request
source = urllib.request.urlopen('https://www.oddsshark.com/nfl/odds').read()
soup = BeautifulSoup(source, 'html.parser')
results = soup.find_all(class_ = "op-item op-spread op-opening")
for result in (results):
print(json.loads(result['data-op-info']).items())
我在最后使用了列印,因為我試圖僅提取行值并查看它。
請注意,此站點上有一個類似的問題,但該解決方案僅適用于一個 div。如果變數有多個 div,它將失敗。
如何使用 Beautifulsoup 決議網頁上 {} 之間的資訊
uj5u.com熱心網友回復:
你快到了。看看我在哪里有串列理解來捕獲結果然后使用json_normalize()
import json
from bs4 import BeautifulSoup
import urllib.request
source = urllib.request.urlopen('https://www.oddsshark.com/nfl/odds').read()
soup = BeautifulSoup(source, 'html.parser')
results = soup.find_all(class_ = "op-item op-spread op-opening")
rlist = [json.loads(result['data-op-info']) for result in (results)]
pd.json_normalize(rlist)
fullgame firsthalf secondhalf firstquarter secondquarter thirdquarter fourthquarter
0 -4.5 -2.5 -1.5 -0.5 -0.5 -0.5 -0.5
1 4.5 2.5 1.5 0.5 0.5 0.5 0.5
2 7 4 3.5 3 3 2.5 2
3 -7 -4 -3.5 -3 -3 -2.5 -2
4 -3 -3 -2.5 -0.5 -2 -0.5 -0.5
5 3 3 2.5 0.5 2 0.5 0.5
6 3 2.5 0.5 0.5 0.5 0.5 0.5
7 -3 -2.5 -0.5 -0.5 -0.5 -0.5 -0.5
8 -3 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5
9 3 0.5 0.5 0.5 0.5 0.5 0.5
10 -3 -2.5 -1 -0.5 -1 -0.5 -0.5
11 3 2.5 1 0.5 1 0.5 0.5
12 -1 0.5 -0.5 0.5 -0.5 -0.5 -0.5
13 1 -0.5 0.5 -0.5 0.5 0.5 0.5
14 2.5 3.5 3 0.5 2.5 0.5 1
15 -2.5 -3.5 -3 -0.5 -2.5 -0.5 -1
16 4 3 2 0.5 1 0.5 0.5
17 -4 -3 -2 -0.5 -1 -0.5 -0.5
18 -2.5 -0.5 -0.5 0.5 -0.5 -0.5 -0.5
19 2.5 0.5 0.5 -0.5 0.5 0.5 0.5
20 -2.5 -1.5 -0.5 -0.5 -0.5 -0.5 -0.5
21 2.5 1.5 0.5 0.5 0.5 0.5 0.5
22 2.5 1.5 0.5 0.5 0.5 0.5 0.5
23 -2.5 -1.5 -0.5 -0.5 -0.5 -0.5 -0.5
24 1.5 1.5 Ev 0.5 -0.5 -0.5 -0.5
25 -1.5 -1.5 Ev -0.5 0.5 0.5 0.5
26 5.5 3 2.5 0.5 0.5 0.5 0.5
27 -5.5 -3 -2.5 -0.5 -0.5 -0.5 -0.5
28 -3.5 -0.5 Ev -0.5 0.5 0.5 0.5
29 3.5 0.5 Ev 0.5 -0.5 -0.5 -0.5
30 -5
31 5
或者,如果您真的只想要字典中的一個鍵:
rlist = [json.loads(result['data-op-info'])['fullgame'] for result in (results)]
pd.DataFrame({'fullgame': rlist})
fullgame
0 -4.5
1 4.5
2 7
3 -7
4 -3
5 3
6 3
7 -3
8 -3
9 3
10 -3
11 3
12 -1
13 1
14 2.5
15 -2.5
16 4
17 -4
18 -2.5
19 2.5
20 -2.5
21 2.5
22 2.5
23 -2.5
24 1.5
25 -1.5
26 5.5
27 -5.5
28 -3.5
29 3.5
30 -5
31 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/365323.html
標籤:Python 网页抓取 美汤 jupyter-笔记本
上一篇:foreach回圈不列印結果,也不顯示PHP8上的錯誤
下一篇:如何從p標簽中查找元素
