[Sparta] 21.09.13 개발일지 7

novxerim·2021년 11월 10일
0

Sparta

목록 보기
7/9

크롤링 연습

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta


headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://www.genie.co.kr/chart/top200?ditc=D&ymd=20200403&hh=23&rtm=N&pg=1',headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')

for tr in trs:
    title = tr.select_one('td.info > a.title.ellipsis').text.strip()
    rank = tr.select_one('td.number').text[0:2].strip()
    artist = tr.select_one('td.info > a.artist.ellipsis').text
    print(rank, title, artist)

https://www.genie.co.kr/chart/top200?ditc=D&ymd=20200403&hh=23&rtm=N&pg=1

지니 차트 크롤링 연습.
어렵지 않았음


파이썬 공백 제거

.strip() 을 넣어준다 꼭 괄호까지 써야함!
(title.text) --> print(title.text.strip())
나중에 .text.strip()은 윗줄 끝으로 옮겨줘도 됨


soup = BeautifulSoup(data.text, 'html.parser')

trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')

for tr in trs:

title = tr.select_one('td.info > a.title.ellipsis')

tbody > tr:nth-child...어쩌구 나오는데 tr까지만 입력.
trs = soup.select('copy_selector복사') << ' 필수
반복하게 할 때 for tr in trs:


파이썬 문자열 자르기

copy_seletor에서 특정 줄만 출력하고 싶을 때
split('')[0] 은 문자열을 나눔
str[0:5] 0부터 5번째 글자까지.

rank = tr.select_one('td.number').text[0:2].strip()

이런식으로 사용

profile
블로그 이전했습니다. https://yerimi11.tistory.com/

0개의 댓글