1. requests라는 패키지를 설치 일종의 ajax역활 

사용법

import requests # requests 라이브러리 설치 필요

r = requests.get('http://spartacodingclub.shop/sparta_api/seoulair')
rjson = r.json()

rows = rjson['RealtimeCityAir']['row']

for row in rows:
    gu_name = row['MSRRGN_NM']
    gu_mise = row['IDEX_MVL']
    if gu_mise < 60:
        print(gu_name,gu_mise)

 

2. bs4 (크롤링을 하기위한 패키지 설치)

import requests
from bs4 import BeautifulSoup

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://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829', headers=headers)

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

movies = soup.select("#old_content > table > tbody > tr")

for movie in movies:
    a = movie.select_one("td.title > div > a")
    if a is not None:
        print(a.text)

2.5  meta라는 코드를 심어넣어질 수도 있는데 property나 다른 속성으로 찾아서 쉽게 크롤링을 할 수도 있다.

@app.route("/movie", methods=["POST"])
def movie_post():
    url = request.form['url']
    data = requests.get(url, headers=headers)
    soup = BeautifulSoup(data.text, 'html.parser')

    title = soup.select_one('meta[property="og:title"]')['content']
    image = image = soup.select_one('meta[property="og:image"]')['content']
    description = description = soup.select_one('meta[property="og:description"]')['content']
    star = request.form['star']
    comment = request.form['comment']

    doc = {
        'title': title,
        'image': image,
        'description': description,
        'star': star,
        'comment': comment
    }
    db.movies.insert_one(doc)



    return jsonify({'msg':'POST 연결 완료!'})

3.mongoDB 클라우드

 

Cloud: MongoDB Cloud

 

account.mongodb.com

 

4. db연결

dnspython , pymongo 패키지 설치 및 기본 문법

from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:sparta@sparta.rffmf.mongodb.net/sparta?retryWrites=true&w=majority')
db = client.dbsparta


# 저장 - 예시
doc = {'name':'bobby','age':21}
db.users.insert_one(doc)

# 한 개 찾기 - 예시
user = db.users.find_one({'name':'bobby'})

# 여러개 찾기 - 예시 ( _id 값은 제외하고 출력)
all_users = list(db.users.find({},{'_id':False}))

# 바꾸기 - 예시
db.users.update_one({'name':'bobby'},{'$set':{'age':19}})

# 지우기 - 예시
db.users.delete_one({'name':'bobby'})

 

5. 숙제  크롤링

import requests
from bs4 import BeautifulSoup

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=M&rtm=N&ymd=20210701', headers=headers)

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

#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.number  순위
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.title.ellipsis 제목
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.artist.ellipsis 가수이름


music = soup.select("#body-content > div.newest-list > div > table > tbody > tr")
# print(music)
for value in music:
    number = value.select_one('td.number')
    title = value.select_one('td.info > a.title.ellipsis')
    singer = value.select_one('td.info > a.artist.ellipsis')
    print(number.text[0:2].strip(), title.text.strip(), singer.text.strip())

1 바라만 본다 MSG워너비 (M.O.M)
2 Next Level aespa
3 신호등 이무진
4 Weekend 태연 (TAEYEON)
5 치맛바람 (Chi Mat Ba Ram) 브레이브걸스 (Brave girls)
6 Butter 방탄소년단
7 나를 아는 사람 MSG워너비 (정상동기)
8 Permission to Dance 방탄소년단
9 비 오는 날 듣기 좋은 노래 (Feat. Colde) 에픽하이 (EPIK HIGH)
10 헤픈 우연 헤이즈 (Heize)
11 하루만 더 빅마마 (Big Mama)
12 비와 당신 이무진
13 Alcohol-Free TWICE (트와이스)
14 롤린 (Rollin') 브레이브걸스 (Brave girls)
15 19금
                                            
                                        
                                        
                                    
                                    Peaches (Feat. Daniel Caesar & Giveon) Justin Bieber
16 Dun Dun Dance 오마이걸 (OH MY GIRL)
17 Dynamite 방탄소년단
18 라일락 아이유 (IU)
19 안녕 (Hello) 조이 (JOY)
20 추적이는 여름 비가 되어 장범준
21 운전만해 (We Ride) 브레이브걸스 (Brave girls)
22 Celebrity 아이유 (IU)
23 러브 (Prod. by 로코베리) 로꼬 & 이성경
24 Bad Habits Ed Sheeran
25 상상더하기 MSG워너비
26 ASAP STAYC (스테이씨)
27 상상더하기 라붐 (LABOUM)
28 밤이 되니까 원슈타인
29 Timeless SG워너비
30 좋아좋아 조정석
31 Savage Love (Laxed - Siren Beat) (BTS Remix) Jawsh 685 & Jason Derulo & 방탄소년단
32 다정히 내 이름을 부르면 경서예지 & 전건호
33 내 손을 잡아 아이유 (IU)
34 사이렌 Remix (Feat. UNEDUCATED KID & Paul Blanco) 호미들
35 At My Worst Pink Sweat$
36 작은 것들을 위한 시 (Boy With Luv) (Feat. Halsey) 방탄소년단
37 OHAYO MY NIGHT 디핵 (D-Hack) & PATEKO
38 가을 우체국 앞에서 김대명
39 나는 너 좋아 장범준
40 멜로디 ASH ISLAND
41 Blueming 아이유 (IU)
42 밝게 빛나는 별이 되어 비춰줄게 송이한
43 에잇 (Prod. & Feat. SUGA of BTS) 아이유 (IU)
44 2002 Anne-Marie
45 LOVE DAY (2021) (바른연애 길잡이 X 양요섭, 정은지) 양요섭 & 정은지
46 아로하 조정석
47 흔들리는 꽃들 속에서 네 샴푸향이 느껴진거야 장범준
48 이제 나만 믿어요 임영웅
49 낙하 (With 아이유) AKMU (악뮤)
50 Off My Face Justin Bieber

복사했습니다!