Programming/Python

Python 4강 - 통신

상맹 2021. 9. 13. 21:15
반응형

pip --version : 환경변수가 잡혀 있는지 확인 할수 있다.

Python 3.9 확인가능

pip install requests : 파이썬 모듈인 requests 설치(라이브러리), 통신을 위해선 무조건 필요

 

 

requests

Python HTTP for Humans.

pypi.org

사이트에서도 설치 가능!

 


1. api 불러오기

(영화 정보 JSON 링크)

https://yts.mx/api/v2/list_movies.json?sort_by=rating&page_number=1&limit=20

 

JSON 쉽게 보기(크롬 확장프로그램)

https://github.com/tulios/json-viewer

 

uri 입력

 

 

2. json으로 parsing 하기

 

3. 필요한 data 정제 하기 => list type(무비만 정제)

 

4. 첫번째 영화의 제목, 평점 출력

 

5. 소스코드

import requests

url = '''
https://yts.mx/api/v2/list_movies.json?sort_by=rating&page_number=1&limit=20
'''


# print(movies)
# print(movies.status_code)
# print(movies.text)
# print(movies.content)
# print(movies.content)
# print(movies.json)

response = requests.get(url)
responseDIct = response.json() # json으로 parsing => dict로 받는다.

movies = responseDIct["data"]["movies"]

print(type(movies)) # list type !!! => list로 다루기

# 첫번째 영화
movie1 = movies[0]

# 영화 제목 뽑기
movie1Title = movie1["title"]
print(movie1Title)

# 영화 평점 뽑기
movie1Rating = movie1["rating"]
print(movie1Rating)

 

6. 연습 문제 

 

# 20개의 영화 데이터의 제목, 평점, 러닝 시간,미디엄-커버-이미지

# 반복문을 돌려서 Console에 예쁘게 출력

# 구분(===================================================)

 

import requests

url = '''
https://yts.mx/api/v2/list_movies.json?sort_by=rating&page_number=1&limit=20
'''

response = requests.get(url)
responseDIct = response.json()

movies = responseDIct["data"]["movies"]

for movie in movies:
    print("제목 : " + movie["title"])
    print("평점 : " + str(movie["rating"]) + "점")
    print("러닝시간 :" + str(movie["runtime"]) + "분")
    print("사진 : " + movie["medium_cover_image"])
    print("="*50)

결과값 각 영화별로 구분되어서 출력되어진 모습

 

반응형