鱼C论坛

 找回密码
 立即注册
查看: 205|回复: 2

通过python爬取https://sofifa.com/所有的球员数据

[复制链接]
发表于 2024-4-20 22:00:08 | 显示全部楼层 |阅读模式
40鱼币
本帖最后由 zchb258 于 2024-4-20 22:01 编辑

本人80后和一些球友常玩这个实况10游戏,因为球员和球员数据总是不断更新,单方面手动复制粘贴工程量很大,下面这篇文章很棒但我实在看不懂,看得有点晕头转向,想请各位大神结合文章出一下完整版,或给个教程,谢谢了

这是原链接https://mp.weixin.qq.com/s/1KX3dw3cfX1J7vk0andL8A
或许看图片文章



用PYTHON爬取的是FIFA网站的球员数据[1].jpg
用PYTHON爬取的是FIFA网站的球员数据[2].jpg
用PYTHON爬取的是FIFA网站的球员数据[3].jpg
用PYTHON爬取的是FIFA网站的球员数据[4].jpg
用PYTHON爬取的是FIFA网站的球员数据[5].jpg
用PYTHON爬取的是FIFA网站的球员数据[6].jpg
用PYTHON爬取的是FIFA网站的球员数据[7].jpg
用PYTHON爬取的是FIFA网站的球员数据[8].jpg
用PYTHON爬取的是FIFA网站的球员数据[9].jpg
用PYTHON爬取的是FIFA网站的球员数据[10].jpg
用PYTHON爬取的是FIFA网站的球员数据[11].jpg
用PYTHON爬取的是FIFA网站的球员数据[12].jpg
用PYTHON爬取的是FIFA网站的球员数据[13].jpg
用PYTHON爬取的是FIFA网站的球员数据[14].jpg
用PYTHON爬取的是FIFA网站的球员数据[15].jpg
用PYTHON爬取的是FIFA网站的球员数据[16].jpg
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-4-20 22:01:17 | 显示全部楼层
嗨!我了解你的问题。爬取网页数据是一个常见的需求,可以通过Python中的requests库来实现。下面是一个简单的示例代码,用于从https://sofifa.com/网站上爬取所有球员数据:

  1. import requests
  2. from bs4 import BeautifulSoup

  3. url = "https://sofifa.com/"

  4. # 发送HTTP请求
  5. response = requests.get(url)

  6. # 解析HTML
  7. soup = BeautifulSoup(response.text, "html.parser")

  8. # 获取球员数据所在的标签
  9. player_divs = soup.find_all("div", class_="col-name")

  10. # 遍历每个球员标签,并提取数据
  11. for player_div in player_divs:
  12.     # 提取球员名字和评分
  13.     name = player_div.a.text.strip()
  14.     rating = player_div.parent.find("div", class_="col col-oa").text.strip()

  15.     # 打印结果
  16.     print(name, rating)
复制代码


在这个示例中,我们使用了requests库发送HTTP请求,然后使用BeautifulSoup库解析返回的HTML文档。通过查找特定的标签和类名,我们可以提取出球员的姓名和评分。

请注意,网站的结构可能会有所变化,所以代码可能需要根据实际情况进行调整。此外,爬取网站数据也需要尊重网站的规则和政策,不要进行过于频繁的请求,以免对网站造成负担。

希望这个简单的示例能帮助到你!如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-4-23 04:39:03 | 显示全部楼层
帮你整合了一下代码:

  1. import requests
  2. from bs4 import BeautifulSoup
  3. import re
  4. import csv

  5. def fetchData(id):
  6.     url = f'https://sofifa.com/player/{str(id)}'
  7.     headers = {
  8.     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36',
  9.     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  10.     'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
  11.     'Referer': 'https://www.google.com/'
  12.     }
  13.     myRequest = requests.get(url)
  14.     soup = BeautifulSoup(myRequest.text,'lxml')
  15.     print(myRequest)
  16.     meta = soup.find(attrs={'name':'description'})
  17.     if meta is None:
  18.         return None
  19.    
  20.     meta = meta['content']
  21.     years = soup.find(name='span',attrs={'class':'bp3-button-text'})
  22.     if meta[:4] != 'FIFA' and (str(years.string)) != "FIFA 23" or meta[:4]=='FIFA':
  23.         return None
  24.    
  25.     info = soup.find(name='div',attrs={'class':'info'})
  26.     playerName = info.h1.string
  27.     myList = [id, playerName]
  28.    
  29.     rawdata = soup.select("#body > div:nth-child(5) > div > div.col.col-12 > div.bp3-card.player > div > div")
  30.     offset = rawdata[0].find_all("span")
  31.     offset = (len(offset))-1
  32.     temp = rawdata[0].text
  33.     temp = re.split('\s+',temp)
  34.     if offset > 0:
  35.         for i in range(offset):
  36.             temp.pop(i)
  37.             
  38.     month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
  39.     mon = temp[3][1:]
  40.     mon = month.index(mon)+1
  41.     day = temp[4][:-1]
  42.     year = temp[5][:-1]
  43.     birthday = [f"{str(year)}/{str(mon)}/{str(day)}"]
  44.     birthday = eval(str(birthday)[1:-1])
  45.     myList.append(birthday)
  46.    
  47.     height = int(temp[6][:-2])
  48.     myList.append(height)
  49.     weight = int(temp[7][:-2])
  50.     myList.append(weight)
  51.    
  52.     rawdata = soup.select("#body > div:nth-child(5) > div > div.col.col-12 > div:nth-child(2) > div > ul")
  53.     temp = rawdata[0].find_all('li',class_="ellipsis")
  54.     preferred_foot = temp[0].contents[1]
  55.     preferred_foot = 1 if (preferred_foot == 'Left') else 2
  56.     myList.append(preferred_foot)
  57.    
  58.     skill_move_level = temp[2].contents[0]
  59.     myList.append(int(skill_move_level))
  60.    
  61.     reputation = temp[3].contents[0]
  62.     myList.append(int(reputation))
  63.    
  64.     todostr = temp[4].text
  65.     workrateString = re.split('\s+',todostr)
  66.     wr_att = workrateString[1][4:-1]
  67.     wr_def = workrateString[2]
  68.     wrList = ['Low',"Medium","High"]
  69.     wr_att = wrList.index(wr_att)+1
  70.     wr_def = wrList.index(wr_def)+1
  71.     myList.append(wr_att)
  72.     myList.append(wr_def)
  73.    
  74.     rawdata = soup.select("#body > div:nth-child(5) > div > div.col.col-12 > div.bp3-card.player > img")
  75.     img_url = rawdata[0].get("data-src")
  76.     img_r = requests.get(img_url,stream=True)
  77.     img_name = f"{id}_{playerName}.png"
  78.     with open(f"./{img_name}","wb") as fi:
  79.         for chunk in img_r.iter_content(chunk_size=120):
  80.             fi.write(chunk)
  81.             
  82.     rawdata = soup.select("#body > div:nth-child(5) > div > div.col.col-12 > div.bp3-card.player > div > div > span")
  83.     allPos = ''.join(f"{p.text} " for p in rawdata)
  84.     myList.append(allPos)
  85.    
  86.     rawdata = soup.select("#body > div:nth-child(6) > div > div.col.col-4 > ul > li:nth-child(1) > span")
  87.     bestPos = rawdata[0].text
  88.     myList.append(bestPos)
  89.    
  90.     rawdata = soup.select("#body > div:nth-child(5) > div > div.col.col-12 > div:nth-child(4) > div > h5> a")
  91.     club = rawdata[0].text if len(rawdata)>0 else "没有俱乐部"
  92.     myList.append(club)
  93.    
  94.     rawdata = soup.select("#body > div:nth-child(5) > div > div.col.col-12 > div.bp3-card.player > div > div > a")
  95.     nation = rawdata[0].get("title") if len(rawdata)>0 else "其他国家"
  96.     myList.append(nation)
  97.    
  98.     rawdata = soup.select('#body>div:nth-child(6)>div>div.col.col-12')
  99.     data = rawdata[0].find_all(class_=re.compile('bp3-tag p'))
  100.     myList.extend(allatt.text for allatt in data)
  101.    
  102.     return myList

  103. def dealWithData(dataToWrite):
  104.     header_list = ['id','name','birthday','height','weight','preferred_foot',"skill_move_level","reputation","wr_att","wr_def",'Positions','Best Position','Club',"nation",'Crossing','Finishing','Heading Accuracy', 'Short Passing','Volleys','Dribbling','Curve', 'FK Accuracy','Long Passing','Ball Control','Acceleration','Sprint Speed','Agility','Reactions','Balance','Shot Power','Jumping','Stamina','Strength','Long Shots','Aggression','Interceptions','Positioning','Vision','Penalties','Composure','Defensive Awareness','Standing Tackle','Sliding Tackle','GK Diving','GK Handling','GK Kicking','GK Positioning','GK Reflexes']
  105.     with open('./output.csv', 'a+', encoding='utf-8-sig', newline='') as f:
  106.         writer = csv.writer(f)
  107.         writer.writerow(header_list)
  108.         writer.writerows(dataToWrite)

  109. def getPlayerID(key):
  110.     url = f"https://sofifa.com/players?keyword={str(key)}"
  111.     myRequest = requests.get(url)
  112.     soup = BeautifulSoup(myRequest.text,'lxml')
  113.     playerTable = soup.select("#body>div.center>div>div.col.col-12>div>table>tbody")
  114.     data = playerTable[0].contents
  115.     playersCandicate = []
  116.    
  117.     if len(data) > 0:
  118.         for p in data:
  119.             id = p.find("img")["id"]
  120.             name = p.find("a")["aria-label"]
  121.             ovr = p.find(attrs={"data-col":"oa"}).get_text()
  122.             playersCandicate.append([id,name,ovr])
  123.     else:
  124.         print("not found")
  125.         playersCandicate.append(["not found","the name you're searching is >>", key])
  126.         
  127.     return playersCandicate

  128. if __name__ == "__main__":
  129.     # 通过递增ID搜索
  130.     for start in range(20000, 40000, 1000):  # 每次爬取1000个球员
  131.         soData = []
  132.         for s in range(start, start + 1000):
  133.             l = fetchData(s)
  134.             if l != None:
  135.                 soData.append(l)
  136.         dealWithData(soData)
  137.         time.sleep(60)  # 爬取完一批次后,休眠60秒
复制代码

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-4 13:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表