2023 공부한것들
[python] [야구시뮬레이터] [결과] 스크래핑한 타자들의 성적 몽고db에 저장하기 (bs4. pymongo 등)
ramona
2023. 6. 5. 17:01
728x90
728x90
항해 99에서 배운 몽고디비 연결하기
내 야구시뮬레이터 프로젝트에도 괜찮을 것 같아서 써먹기로 했다
방금 전 게시물에서 썼던, 모든 선수들을 저장하는 코드를 조금 바꿔서 몽고디비에 저장할 수 있도록 햇다
중간에 db=client.baseball (db를 설정해주는 문장)을 적지 않아 막혔는데 항해 99에서 실습했던 파일을 찾아보니 이게 오류였구나... 했다 ^^ 허허
처음부터 끝까지 내가 적다 보니 코드스니펫 쓰던 시절이 그립다 ~~~~
from pymongo import MongoClient
import requests
from bs4 import BeautifulSoup
team_codes = ["sk", "wo", "lg", "ht","nc", "ss","hh","lt","kt","ob"]
client = MongoClient('mongodb+srv://sparta:test@sparta.rqx1qlk.mongodb.net/?retryWrites=true&w=majority')
db = client.baseball
for team_code in team_codes:
url = f"http://eng.koreabaseball.com/Stats/BattingByTeams.aspx?codeTeam={team_code}"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find_all('table')[0]
data = []
tr_tags = table.find_all('tr')
for tr in tr_tags:
td_tags = tr.find_all('td')
row = {}
for td in td_tags:
title = td.get('title')
if title:
row[title] = td.text
elif 'stats_player' in td.get('class', []):
row['Player'] = td.text
if row:
data.append(row)
collection = db[team_code]
collection.insert_many(data)
728x90
300x250