프로젝트 명 : 빅데이터 기반 모의 야구경기 시뮬레이터
목표 1. 선수명단 스크래핑하기
1차 시도
프로그램은 영어로 제공될것이기에 영어 이름을 스크래핑해야했다.
http://eng.koreabaseball.com/Teams/PlayerSearch.aspx
KBO
eng.koreabaseball.com
정말 좋은 사이트를 찾았다.
각 구단별 선수들이 모두 나와있었고 영어 기반이다..
바로 코드를 짜봤다.
import requests
from bs4 import BeautifulSoup
# 팀 목록
teams = {
'두산': '1',
'KIA': '2',
'KT': '3',
'LG': '4',
'NC': '5',
'롯데': '6',
'삼성': '7',
'SSG': '8',
'키움': '9',
'한화': '10'
}
# 선수 정보를 저장할 리스트
player_list = []
# 각 팀별로 스크래핑 수행
for team_name, team_id in teams.items():
url = f'http://eng.koreabaseball.com/Teams/PlayerSearch.aspx?pcode={team_id}'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 각 포지션별 탭에서 선수 정보 스크래핑
positions = ['Pitcher', 'Catcher', 'Infielder', 'Outfielder']
for position in positions:
tab_id = soup.find('a', text=position)['href'].split('#')[1]
tab_content = soup.find('div', {'id': tab_id})
# 선수 정보 스크래핑
players = tab_content.find_all('tr')[1:]
for player in players:
data = player.find_all('td')
name = data[1].text.strip()
info = data[2].text.strip()
# 선수 정보를 딕셔너리로 저장 후 리스트에 추가
player_info = {
'Team': team_name,
'Name': name,
'Info': info
}
player_list.append(player_info)
# 결과 출력
for player in player_list:
print(f"팀: {player['Team']}, 이름: {player['Name']}, 정보: {player['Info']}")
엑셀에 저장하는 기능까지는 구현하지 않았다
첫번째 목표는 출력해내기
이런.
이 코드는 soup.select_one() 함수를 사용하여 CSS 선택자를 이용하여 각 탭에 대한 링크를 찾게하고, 이를 통해 정확한 요소를 찾을 수 있으며, 오류가 발생하지 않도록 수정해보았다.
import requests
from bs4 import BeautifulSoup
# 팀 목록
teams = {
'두산': '1',
'KIA': '2',
'KT': '3',
'LG': '4',
'NC': '5',
'롯데': '6',
'삼성': '7',
'SSG': '8',
'키움': '9',
'한화': '10'
}
# 선수 정보를 저장할 리스트
player_list = []
# 각 팀별로 스크래핑 수행
for team_name, team_id in teams.items():
url = f'http://eng.koreabaseball.com/Teams/PlayerSearch.aspx?pcode={team_id}'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 각 포지션별 탭에서 선수 정보 스크래핑
positions = ['Pitcher', 'Catcher', 'Infielder', 'Outfielder']
for position in positions:
tab_link = soup.select_one(f'a[href*="#{position}"]')
if tab_link:
tab_id = tab_link['href'].split('#')[1]
tab_content = soup.find('div', {'id': tab_id})
# 선수 정보 스크래핑
players = tab_content.find_all('tr')[1:]
for player in players:
data = player.find_all('td')
name = data[1].text.strip()
info = data[2].text.strip()
# 선수 정보를 딕셔너리로 저장 후 리스트에 추가
player_info = {
'Team': team_name,
'Name': name,
'Info': info
}
player_list.append(player_info)
# 결과 출력
for player in player_list:
print(f"팀: {player['Team']}, 이름: {player['Name']}, 정보: {player['Info']}")
출력이 되지 않았다... 오류는 안 뜨는데;...
고군분투 끝에 해냈다
import requests
from bs4 import BeautifulSoup
# 웹 페이지 URL
url = "http://eng.koreabaseball.com/Teams/PlayerSearch.aspx"
# 선수 이름
player_name = "BAEK Seung Geon"
# GET 요청으로 HTML 가져오기
response = requests.get(url)
html = response.text
# BeautifulSoup을 사용하여 HTML 파싱
soup = BeautifulSoup(html, "html.parser")
# 선수 이름에 해당하는 요소 찾기
player_element = soup.find("a", text=player_name)
# 선수 정보가 없으면 종료
if player_element is None:
print("선수를 찾을 수 없습니다.")
exit(0)
# 선수 정보가 있는 table row 찾기
player_row = player_element.find_parent("tr")
# 선수 정보 추출
player_info = {}
for td in player_row.find_all("td"):
# 각 td 요소의 title 속성을 가져와서 선수 정보에 추가
title = td.get("title")
if title:
player_info[title] = td.text.strip()
# 가져온 선수 정보 출력
print("선수 이름:", player_name)
for key, value in player_info.items():
print(key + ":", value)
백성준의 정보를 출력해냈다
선수 이름: BAEK Seung Geon
no.: 59
position: Pitcher
born: 2000-10-29
ht, wt: 183cm, 85kg
이제는 리스트의 모든 선수들을 출력할 차례
import requests
from bs4 import BeautifulSoup
# 웹 페이지 URL
url = "http://eng.koreabaseball.com/Teams/PlayerSearch.aspx"
# GET 요청으로 HTML 가져오기
response = requests.get(url)
html = response.text
# BeautifulSoup을 사용하여 HTML 파싱
soup = BeautifulSoup(html, "html.parser")
# 모든 선수 요소를 찾음
player_elements = soup.select('th[title="player"]')
# 모든 선수에 대한 정보를 저장할 리스트
all_players_info = []
for player_element in player_elements:
player_name = player_element.text.strip()
# 선수 정보가 있는 table row 찾기
player_row = player_element.find_parent("tr")
# 선수 정보 추출
player_info = {'name': player_name}
for td in player_row.find_all("td"):
# 각 td 요소의 title 속성을 가져와서 선수 정보에 추가
title = td.get("title")
if title:
player_info[title] = td.text.strip()
# 선수 정보를 리스트에 추가
all_players_info.append(player_info)
# 가져온 모든 선수의 정보 출력
for player_info in all_players_info:
print("선수 이름:", player_info.pop('name'))
for key, value in player_info.items():
print(key + ":", value)
print() # 각 선수 정보 사이에 공백 라인을 출력
코드를 조금 만져서 성공했다
선수 이름: BAEK Seung Geon
no.: 59
position: Pitcher
born: 2000-10-29
ht, wt: 183cm, 85kg
선수 이름: CHO Sung Hun
no.: 43
position: Pitcher
born: 1999-03-22
ht, wt: 188cm, 85kg
선수 이름: CHOI Min Jun
no.: 67
position: Pitcher
born: 1999-06-11
ht, wt: 178cm, 83kg
선수 이름: CHUNG Dong Yoon
no.: 62
position: Pitcher
born: 1997-10-22
ht, wt: 193cm, 103kg
선수 이름: ELIAS Roenis
no.: 25
position: Pitcher
born: 1988-08-01
ht, wt: 185cm, 92kg
선수 이름: HAN Doo Sol
no.: 34
position: Pitcher
born: 1997-01-15
ht, wt: 177cm, 86kg
선수 이름: IM Jun Seob
no.: 48
position: Pitcher
born: 1989-07-16
ht, wt: 181cm, 88kg
선수 이름: JEON Young Jun
no.:
position: Pitcher
born: 2002-04-16
ht, wt: 192cm, 110kg
선수 이름: JUNG Sung Gon
no.: 1
position: Pitcher
born: 1996-07-10
ht, wt: 181cm, 80kg
선수 이름: KIM Do Hyun
no.: 68
position: Pitcher
born: 2003-05-24
ht, wt: 179cm, 89kg
선수 이름: KIM Joo On
no.: 11
position: Pitcher
born: 1996-12-08
ht, wt: 187cm, 89kg
선수 이름: KIM Ju Han
no.: 21
position: Pitcher
born: 1993-02-03
ht, wt: 184cm, 93kg
선수 이름: KIM Kwang Hyun
no.: 29
position: Pitcher
born: 1988-07-22
ht, wt: 188cm, 88kg
선수 이름: KIM Tae Hoon
no.: 51
position: Pitcher
born: 1990-05-19
ht, wt: 176cm, 88kg
선수 이름: KO Hyo Jun
no.: 15
position: Pitcher
born: 1983-02-08
ht, wt: 179cm, 81kg
선수 이름: LEE Geun Wook
no.: 16
position: Pitcher
born: 1995-02-13
ht, wt: 182cm, 85kg
선수 이름: LEE Ki Soon
no.: 39
position: Pitcher
born: 2003-05-14
ht, wt: 174cm, 74kg
선수 이름: LEE Ro Un
no.: 92
position: Pitcher
born: 2004-09-11
ht, wt: 185cm, 105kg
선수 이름: LEE Won Joon
no.: 66
position: Pitcher
born: 1998-07-02
ht, wt: 190cm, 98kg
선수 이름: MCCARTY Kirk
no.: 33
position: Pitcher
born: 1995-10-12
ht, wt: 173cm, 83kg
선수 이름: MOON Seung Won
no.: 42
position: Pitcher
born: 1989-11-28
ht, wt: 180cm, 88kg
선수 이름: NOH Kyung Eun
no.: 38
position: Pitcher
born: 1984-03-11
ht, wt: 187cm, 100kg
선수 이름: OH Won Seok
no.: 47
position: Pitcher
born: 2001-04-23
ht, wt: 182cm, 80kg
선수 이름: PARK Jong Hun
no.: 50
position: Pitcher
born: 1991-08-13
ht, wt: 186cm, 90kg
선수 이름: PARK Min Ho
no.: 41
position: Pitcher
born: 1992-02-25
ht, wt: 185cm, 95kg
선수 이름: PARK Sang Hoo
no.: 64
position: Pitcher
born: 2003-08-05
ht, wt: 187cm, 87kg
선수 이름: PARK Si Hoo
no.: 46
position: Pitcher
born: 2001-05-10
ht, wt: 182cm, 88kg
선수 이름: ROMERO Enny
no.:
position: Pitcher
born: 1991-01-24
ht, wt: 190cm, 105kg
선수 이름: SEO Dong Min
no.: 18
position: Pitcher
born: 1994-03-07
ht, wt: 186cm, 90kg
선수 이름: SEO Jin Yong
no.: 22
position: Pitcher
born: 1992-10-02
ht, wt: 184cm, 88kg
선수 이름: SHIN Heon Min
no.: 49
position: Pitcher
born: 2002-07-19
ht, wt: 187cm, 88kg
선수 이름: SONG Young Jin
no.: 98
position: Pitcher
born: 2004-05-28
ht, wt: 185cm, 90kg
선수 이름: YUN Tae Hyeon
no.: 30
position: Pitcher
born: 2003-10-10
ht, wt: 189cm, 93kg
이제 얘를 엑셀로 저장해보려고 한다
우리 팀은 아니지만 쓱의 모든 투수들의 정보를 출력해냈다
'2023 공부한것들' 카테고리의 다른 글
[야구시뮬레이터] [결과] 모든 투수진 스크래핑해 엑셀 파일로 저장하기 (0) | 2023.06.03 |
---|---|
[야구시뮬레이터] [결과] 한 팀의 투수진 스크래핑하기 (0) | 2023.06.03 |
[python] genie music 차트 스크래핑 후 엑셀 저장 (beautifulsoup/pandas) + user-Agent 헤더(웹 브라우저로 둔갑하기) (0) | 2023.06.03 |
[정보보안] DNS란?/DNS 정보 탈취하기/DNS 유출 예방법 (0) | 2023.03.07 |
[Tor/Darkweb] 다크웹이란?/토르 추적 방식 (1) | 2023.03.01 |