Programming/Python 웹 스크래퍼 만들기

Python Requests, Get 복습

2022. 11. 15. 21:00

4.9 Recap

 

for 반복문은 sequence 안의 각 item 으로 코드를 실행시킬 수 있는 방법이다.

 

from requests import get       

websites = (                    
    'google.com',              
    'https://airbnb.com',
    'facebook.com',
    'https://naver.com'
)

results ={}

for website in websites:
    if not website.startswith('https://'):
        website = f"https://{website}"
    
    response = get(website)
    
    if response.status_code == 200:
        results[website] = "OK"
    else:
        results[website] = "FAILED"

print(results)

from requests import get  →  requests 모듈사용, get 기능 사용 ( get은 1개의 url을 받고 웹사이트를 가져온다 )

websites 라는 튜플 안에 구글, 에어비엔비, 페이스북, 네이버 URL 넣음, https 있는것도 있고 없는것도 있고,

results ={} → results 라는 빈 딕셔너리 생성

for website in websites: → website 변수로 websites 안의 구글,에어비엔비,페이스북,네이버 등 아이템을 반복할거다.

for potatos in websites: → potatos 변수로 websites 안의 구글,에어비엔비,페이스북,네이버 등 아이템을 반복할거다.

website 라는 변수는 관습적으로 사용할 뿐 변수명은 사용자가 마음대로 정하면된다.

 

for website in websites:
    if not website.startswith('https://'):  → website 의 시작문자가 https:// 가 아니면
        website = f"https://{website}"      → webstie 에 https://website 를 넣어라 ( https:// 문자를 붙여서 넣어라 )

 

 

'google.com', 
'facebook.com',

위에 두개 url 은 https:// 문자가 앞에 없으니 붙여서 website 변수에 저장된다.

 

response = get(website)  →  get 사용해서 website 불러온것을 response 변수에 넣어라

 

if response.status_code == 200: → response 로 불러온 값의 웹사이트 HTTP 상태코드가 200 (정상) 이면 

results[website] ="OK" →  results 라는 딕셔너리에 website 는 key 로, OK 는 value 값으로 넣어라 (추가해라)

 

results[website] == results['https://google.com'] 라고 생각하면 된다.

구글,에어비엔비,페이스북,네이버가 돌아가면서 들어간다.

 

else: → 아니면

results[website]="FAILED" →  results 라는 딕셔너리에 website 는 key 로, FAILED 는 value 값으로 넣어라 (추가해라)

 

print(results) 해서 results 딕셔너리 출력하면

 

{'https://google.com': 'OK', 'https://airbnb.com': 'OK', 'https://facebook.com': 'OK', 'https://naver.com': 'OK'}

'https://google.com'  이라는 key 값과

OK 라는 value 값이 나온다.

각각 다른 웹사이트들의 상태가 key 와 value 로 출력된다.

4개 url 모두 https 가 붙은 정상 url 이므로 OK 값이 key로 출력된다.

 

for 문 안의 코드가 websites 튜플의 아이템에 각각에 대해 총 4번 실행되면 results 라는 딕셔너리에 상태값과 함께 출력된다.

 

 

챌린지

response 는 여러 상태 코드가 있다.현재 코드는 200이 아니면 전부 에러라고 생각한다.

각각 상태코드에 맞는 반응들을 출력하는 코드를 작성해본다.

 

from requests import get        

websites = (                    
    'google.com',              
    'https://airbnb.com',
    'facebook.com',
    'https://naver.com',
    'https://daum.net'
)

results = {}

for website in websites:
    if not website.startswith('https://'):
        website = f"https://{website}"
    
    response = get(website)
    if 100 <= response.status_code < 200:
        results[website] = "Information reponse"
    elif 200 <= response.status_code < 300:
        results[website] = "Success"
    elif 300 <= response.status_code < 400:
        results[website] = "Redirect"
    elif 400 <= response.status_code < 500:
        results[website] = "Client Error"
    elif 500 <= response.status_code < 600:
        results[website] = "Server Error"

print(results)

혹은 status_number 라는 변수를 추가로 만들어서 startswith 메서드를 사용하여  시작 숫자로 판별하여 출력 할 수 있다.

from requests import get

websites = (                    
    'google.com',              
    'https://airbnb.com',
    'facebook.com',
    'https://naver.com',
    'https://daum.net'
)

results = {}

for website in websites :
    if not website.startswith("https://"):
        website = f"https://{website}"
    
    response = get(website)

    status_number = str(response.status_code)
    
    if status_number.startswith("1"):
        results[website] = "Information reponse"
    elif status_number.startswith("2"):
        results[website] = "Success"
    elif status_number.startswith("3"):
        results[website] = "Redirect"
    elif status_number.startswith("4"):
        results[website] = "Client error"
    else :
        results[website] = "Server Error"

print(results)

실제 사이트 말고 http 상태코드를 입력하면 그 값을 반환해주는 사이트가 있어 사용해보았다.

from requests import get

websites = (                    
    'httpstat.us/101',              
    'httpstat.us/202',
    'httpstat.us/303',
    'httpstat.us/404',
    'httpstat.us/505',
)

results = {}

for website in websites :
    if not website.startswith("https://"):
        website = f"https://{website}"
    
    response = get(website)

    status_number = str(response.status_code)
    
    if status_number.startswith("1"):
        results[website] = "Information reponse"
    elif status_number.startswith("2"):
        results[website] = "Success"
    elif status_number.startswith("3"):
        results[website] = "Redirect"
    elif status_number.startswith("4"):
        results[website] = "Client error"
    else :
        results[website] = "Server Error"

print(results)

출력값:

{'https://httpstat.us/101': 'Information reponse', 'https://httpstat.us/202': 'Success', 'https://httpstat.us/303': 'Success', 'https://httpstat.us/404': 'Client error', 'https://httpstat.us/505': 'Server Error'}

 

각 상태코드에 맞는 출력값이 나왔다.

'Programming > Python 웹 스크래퍼 만들기' 카테고리의 다른 글

Python BeautifulSoup  (0) 2022.11.17
Python WebScrapper Introduction  (1) 2022.11.16
Python Requests  (0) 2022.11.14
Python For Loops  (0) 2022.11.11
Python List, Tuple, Dict 복습  (0) 2022.11.10
'Programming/Python 웹 스크래퍼 만들기' 카테고리의 다른 글
  • Python BeautifulSoup
  • Python WebScrapper Introduction
  • Python Requests
  • Python For Loops
Security Engineer
Security Engineer
IT 공부
Security Engineer
IT-log
Security Engineer
전체
오늘
어제
  • 분류 전체보기 (178)
    • Programming (39)
      • Python 웹 스크래퍼 만들기 (39)
    • IT 지식 (70)
      • IT 정보 (28)
      • CS 기초 (24)
      • 운영체제 (8)
      • IT 인프라 기초 (10)
    • 보안 (46)
      • 악성코드 분석 (10)
      • Bandit 워게임 (25)
      • 취미로 해킹 2 (6)
      • 환경 구축 (4)
      • PoC 분석 (1)
    • 웹 해킹 (23)
      • 웹 기초 지식 (8)
      • SQL 기본 (2)
      • 웹 해킹 및 시큐어 코딩 기초 (13)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 악성코드 분석
  • 운영체제
  • Def
  • CS
  • it 운영
  • 웹 해킹
  • 모의해킹
  • bandit
  • Selenium
  • 취미로 해킹
  • 파이썬
  • IT 인프라
  • flask
  • Python
  • WarGame
  • 악성코드
  • Beautifulsoup
  • 리눅스
  • 워게임
  • Web
  • overthewire
  • 해킹
  • 웹 개발
  • webScrapper
  • CSS
  • 컴퓨터
  • 시큐어 코딩
  • 취미로해킹
  • CS 기초
  • HTML

최근 댓글

최근 글

hELLO · Designed By 정상우.
Security Engineer
Python Requests, Get 복습
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.