본문 바로가기

Data handling/Web crawling

[크롤링] 엄청 쉽고 간단한 크롤링 방법. 꿀팁. 라이브러리 필요 없음

반응형

기존 방법

f12를 눌러 사이트의 정보를 탐색한다.

  • selenium을 이용할 경우 xpath를 찾고 고생 끝에 구축한다.
  • beautiful soup를 이용해 해당 정보의 구조를 잘 파악해야 한다.

기존 방법의 단점

  • 힘들다.. 번거롭다
  • 매번 귀찮다.

새로운 방법

KB 부동산 시세를 보는 사이트를 예로 들겠다.

onland.kbstar.com/quics?page=C059652

 

매물·시세 ( KB부동산(LiivON) | 매물·시세 )

KB 정보 제공 한계 및 책임 지적편집도 제공의 한계책임 설명 닫기 본 지적편집도는 공간정보산업진흥원에서 제공하는 데이터를 다음지도에서 편집 제작한 지도입니다. 지역별 최신성, 정확성��

onland.kbstar.com

f12를 누르고 Network를 본다. 

request 방식이 Get일 경우 좀 더 쉽다

해당한다고 생각하는 요소의 Name을 우클릭하고 

링크 주소를 복사한다.

python에선 아래와 같은 코드를 입력하면 json 파일 획득 완료

response = requests.get('복사한 link address를 넣어준다.')
json_data = json.loads(response.text)

Post 방식의 경우 

1. 코드 방식

json으로 받아준다!

import requsts
import json

def web_request(method_name, url, dict_data, is_urlencoded=True):
    """Web GET or POST request를 호출 후 그 결과를 dict형으로 반환 """
    method_name = method_name.upper() # 메소드이름을 대문자로 바꾼다 
    if method_name not in ('GET', 'POST'):
        raise Exception('method_name is GET or POST plz...')
        
    if method_name == 'GET': # GET방식인 경우
        response = requests.get(url=url, params=dict_data)
    elif method_name == 'POST': # POST방식인 경우
        if is_urlencoded is True:
            response = requests.post(url=url, data=dict_data, headers={'Content-Type': 'application/x-www-form-urlencoded'})
        else:
            response = requests.post(url=url, data=json.dumps(dict_data), headers={'Content-Type': 'application/json'})
    
    dict_meta = {'status_code':response.status_code, 'ok':response.ok, 'encoding':response.encoding, 'Content-Type': response.headers['Content-Type']}
    if 'json' in str(response.headers['Content-Type']): # JSON 형태인 경우
        return {**dict_meta, **response.json()}
    else: # 문자열 형태인 경우
        return {**dict_meta, **{'text':response.text}}

url  = link_address # 접속할 사이트주소 또는 IP주소를 입력한다 
data = request_body         # 요청할 데이터
response = web_request(method_name='POST', url=url, dict_data=data, is_urlencoded=False)

print(response)
if response['ok'] == True:
    print('ok')
    # 성공 응답 시 액션
else:
    pass
    # 실패 응답 시 액션

json 저장은? 저장할 파일 이름을 인자로 주고 open으로 연후, json.dump를 사용해 json을 저장해준다!

with open("temp.json", "w") as json_file:
    json.dump(response, json_file)

위 코드를 입력하기 번거롭다~ 하시는 분은 아래 참조!

2. 추가적인 프로그램 사용

www.telerik.com/download/fiddler-everywhere

 

Download Fiddler Everywhere Web Debugging Tool by Telerik

Download and install Fiddler Everywhere a web debugging tool. Watch a quick tutorial to get started.

www.telerik.com

fiddler를 사용한다.

관련 사용법은 다른 포스트를 참조하시기 바란다.

blog.naver.com/PostView.nhn?blogId=dlsgh9902&logNo=220657637473&parentCategoryNo=&categoryNo=8&viewDate=&isShowPopularPosts=false&from=postView

 

Fiddler를 이용한 Post 방식 요청!

Fiddler 툴을 이용한 Post 방식 요청에 대하여포스팅 고고!! 일단 2가지만 기억하면됩니다.1)Content-T...

blog.naver.com

 

이 포스트와 유사한 포스트는 아래에 있다.

heodolf.tistory.com/68

 

[크롤링] 직방에서 방찾기 (1) - 데이터 분석

최근 청년전세자금 대출을 이용하여 독립을 해보려고 원룸을 알아보고 있었는데, 대출로 계약할 수 있는 방이 한정적이었다. 검색이라도 할 수 있으면 괜찮은데 검색도 할 수 없어서 직접 대출�

heodolf.tistory.com

 

반응형