1. 程式人生 > 實用技巧 >Python爬取NBA虎撲球員資料

Python爬取NBA虎撲球員資料

虎撲是一個認真而有趣的社群,每天有眾多JRs在虎撲分享自己對籃球、足球、遊戲電競、運動裝備、影視、汽車、數碼、情感等一切人和事的見解,熱鬧、真實、有溫度。

受害者地址

https://nba.hupu.com/stats/players

本文知識點:

  • 系統分析網頁性質
  • 結構化的資料解析
  • csv資料儲存

環境介紹:

  • python 3.6
  • pycharm
  • requests
  • csv

爬蟲案例的一般步驟

  • 1.確定url地址(網頁分析) 完成一半
  • 2.傳送網路請求 requests(js\html\css)
  • 3.資料解析(篩選資料)
  • 4.儲存資料(本地檔案\資料庫)

部分程式碼

匯入工具

import requests  # 第三方工具
import parsel  # 資料解析工具  (css\正則表示式\xpath)
import csv

確定url地址(網頁分析) 完成一半 (靜態網頁\動態網頁)

url = 'https://nba.hupu.com/stats/players/pts/{}'.format(page)

傳送網路請求 requests(js\html\css)

response = requests.get(url=url)
html_data = response.text

資料解析(篩選資料)

selector = parsel.Selector(html_data)
    trs 
= selector.xpath('//tbody/tr[not(@class="color_font1 bg_a")]') for tr in trs: rank = tr.xpath('./td[1]/text()').get() # 排名 player = tr.xpath('./td[2]/a/text()').get() # 球員 team = tr.xpath('./td[3]/a/text()').get() # 球隊 score = tr.xpath('./td[4]/text()').get() # 得分 hit_shot = tr.xpath('
./td[5]/text()').get() # 命中-出手 hit_rate = tr.xpath('./td[6]/text()').get() # 命中率 hit_three = tr.xpath('./td[7]/text()').get() # 命中-三分 three_rate = tr.xpath('./td[8]/text()').get() # 三分命中率 hit_penalty = tr.xpath('./td[9]/text()').get() # 命中-罰球 penalty_rate = tr.xpath('./td[10]/text()').get() # 罰球命中率 session = tr.xpath('./td[11]/text()').get() # 場次 playing_time = tr.xpath('./td[12]/text()').get() # 上場時間 print(rank, player, team, score, hit_shot, hit_rate, hit_three, three_rate, hit_penalty, penalty_rate, session, playing_time) data_dict = { '排名': rank, '球員': player, '球隊': team, '得分': score, '命中-出手': hit_shot, '命中率': hit_rate, '命中-三分': hit_three, '三分命中率': three_rate, '命中-罰球': hit_penalty, '罰球命中率': penalty_rate, '場次': session, '上場時間': playing_time} csv_write.writerow(data_dict) # 想要完整原始碼的同學可以關注我的公眾號:松鼠愛吃餅乾 # 回覆“虎撲NBA”即可免費獲取

執行程式碼,效果如下