티스토리 뷰
Python
자바보다 직관적인 프로그래밍 언어이다. 자바와 다르게 중괄호 등으로 묶이지 않는 간편함으로 들여쓰기가 매우 중요하다.
" ':' 표시는 이후 나오는 내용은 윗줄에 포함입니다."라는 뜻이다. 포함되는 코드는 들여쓰기 되어진다.
def sum(a,b):
return a+b
result = sum(1,2)
print(result)
def (definition의 약자) : 함수를 정의한다.
return : 값을 반환
print() : 값을 출력
<조건문>
def is_adult(age):
if age > 20:
print('성인입니다.')
else:
print('청소년입니다.')
is_adult(15)
people = [{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27}]
for person in people:
if person['age'] > 20:
print(person['name'])
<반복문>
requests 라이브러리를 이용한 코드(html에서 사용했던 ajax와 비슷)
- 미세먼지수치 60 이하인 구이름 출력
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['MSRSTE_NM']
gu_mise = row['IDEX_MVL']
if gu_mise < 60:
print(gu_name, gu_mise)
bs4 라이브러리를 이용한 코드(request로 가져온 html 또는 css의 데이터를 뽑아낼 수 있다)
- 영화 제목 추출
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')
# 코딩 시작 (검사 -> 콘솔 복사 -> copy selector)
#old_content > table > tbody > tr:nth-child(2) > td.title > div > a
#old_content > table > tbody > tr:nth-child(4) > td.title > div > a
movies = soup.select('#old_content > table > tbody > tr')
for movie in movies:
a = movie.select_one('td.title > div > a')
if a != None:
print(a.text)
request & bs4 패키지 참고
'[학습일지] > Python' 카테고리의 다른 글
[학습일지] 웹개발 3-10 ~ 3-16 ( MongoDB 기본 코드) (0) | 2022.07.16 |
---|---|
[학습일지] 웹개발 3-9 ( Python, requests/bs4) (0) | 2022.07.15 |
[학습일지] 웹개발 3-1 ( Ajax, 영화 별점탭) (0) | 2022.07.13 |
[학습일지] 웹개발 2-14 ( Ajax, 날씨 정보) (0) | 2022.07.12 |
[학습일지] 웹개발 2-13 ( Ajax 연습하기3, 이미지 출력하기) (0) | 2022.07.11 |