R語言一鍵爬取英格蘭足球超級聯賽16-17賽季所有比分(基於RCurl)
阿新 • • 發佈:2019-02-04
一、背景交代
本人破廠鐵桿,上週剛被紅軍血虐,並且主隊上賽季戰績不佳,無緣歐冠,實在心如死灰(手動捂臉)。
這次也用RCurl來嘗試爬取一下英超聯賽的所有比分,選取賽季為16-17賽季。
選擇的網站不是大家平時關注多的一些入口網站,而是一家香港的專業足球網站(實時滾球加持buff),
網址為:http://data.7m.cn/database/index_big.htm ,頁面如下:
二、物件定位
1、 一般基本的爬蟲通過html頁面或者解析json去爬取得到所需資料,但是這個網站無法右鍵檢視原始碼和檢查。利用瀏覽器快捷鍵 ctr+shift+I 直接進入檢查介面。
2、 接下來輕車熟路,找到JS,F5重新整理,發現第二個fixgure.js
三、編寫程式碼,解析網址
require(RCurl)
#目標網頁網址
url="http://data2.7m.cn/history_Matches_Data/2016-2017/92/big/fixture.js"
#偽裝表頭
myheader=c("Accept"="text/html, application/xhtml+xml, */*",
"Referer"="http://data2.7m.cn/matches_data/92/big/index.shtml",
"Accept-Language"="zh-CN",
"User-Agent" ="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.48 Safari/537.36 QQBrowser/7.7.31732.400",
"Accept-Encoding"="gzip, deflate",
"Connection"="Keep-Alive"
)
t=basicTextGatherer()
temp=getURL(url,httpHeader=myheader,write=t,verbose=T,.encoding="UTF-8" )
rd<-strsplit(t$value(),"\r\n")
rd[[1]][6]#輪次
rd[[1]][7]#比賽時間
rd[[1]][8]#比分
rd[[1]][11]#主隊
rd[[1]][12]#客隊
#接下來操作js裡面的列表,瘋狂解析
p_round<-regexpr("(\\d,)+(\\d{2},)+\\d{2}",rd[[1]][6])
c_round<-substr(rd[[1]][6],p_round[1],attr(p_round,"match.length")+p_round[1]-1)
rounds<-strsplit(c_round,",")#輪次
p_match_time<-regexpr('\\d{4},\\d{2},\\d{2},\\d{2},\\d{2},\\d{2}\\",(\\"\\d{4},\\d{2},\\d{2},\\d{2},\\d{2},\\d{2}\\",)+(\\"\\d{4},\\d{2},\\d{2},\\d{2},\\d{2},\\d{2})',rd[[1]][7])
c_match_time<-substr(rd[[1]][7],p_match_time[1],attr(p_match_time,"match.length")+p_match_time[1]-1)
match_time<-strsplit(c_match_time,'\\",\\"')#比賽時間
p_scores<-regexpr('(\\d-\\d\\(\\d-\\d\\)\\",)(\\"\\d-\\d\\(\\d-\\d\\)\\",)+(\\"\\d-\\d\\(\\d-\\d\\))',rd[[1]][8])
c_scores<-substr(rd[[1]][8],p_scores[1],attr(p_scores,"match.length")+p_scores[1]-1)
scores<-strsplit(c_scores,'\\",\\"')#比分
p_hometeam<-regexpr('(\\w+\\",)(\\"\\w+\\",)+(\\"\\w+)',rd[[1]][11])
c_hometeam<-substr(rd[[1]][11],p_hometeam[1],attr(p_hometeam,"match.length")+p_hometeam[1]-1)
hometeam<-strsplit(c_hometeam,'\\",\\"')#主隊
p_awayteam<-regexpr('(\\w+\\",)(\\"\\w+\\",)+(\\"\\w+)',rd[[1]][12])
c_awayteam<-substr(rd[[1]][12],p_awayteam[1],attr(p_awayteam,"match.length")+p_awayteam[1]-1)
awayteam<-strsplit(c_awayteam,'\\",\\"')#客隊
data<-matrix(c(rounds[[1]],match_time[[1]],hometeam[[1]],scores[[1]],awayteam[[1]]),ncol=5,nrow=380)
colnames(data)<-c("輪次","比賽時間","主隊","賽果","客隊")
getwd()
write.csv(data,"Super-Leagues.csv")
data
四、得到資料
開啟儲存的csv檔案,資料如下。
接下來可以進一步就某支球隊的情況具體分析,比如隨時間的成績波動、同城死敵較量歷史戰績之類的,同樣這個網站可以一直往前到04-05賽季的歷史資料,相當強大了,至於其他的射手榜、助攻榜之類也可以同樣的操作。