[Python] Open API 활용한 크롤링

2023. 4. 18. 15:53Language/Python

네이버 쇼핑 검색 api 크롤링

import requests # 임포트
import pprint

client_id = 'xxxxxx' # 본인 네이버 Client ID사용
client_secret = 'xxx' # 본인 Client Secret사용

naver_open_api = ' https://openapi.naver.com/v1/search/shop.json?query=갤럭시노트10'
header_params = {"X-Naver-Client-Id":client_id, "X-Naver-Client-Secret":client_secret}
res = requests.get(naver_open_api, headers=header_params)

if res.status_code == 200: # status code 가 200일 때 아래코드 실행
    data = res.json()
    for index, item in enumerate(data['items']):
        print (index + 1, item['title'], item['link'])
else: # status code 가 200 아니면 에러코드 실행
    print ("Error Code:", res.status_code)

1 삼성 <b>갤럭시 노트10</b> 256GB 정품 자급제 SM-N970 https://search.shopping.naver.com/gate.nhn?id=36567812649
2 삼성전자 <b>갤럭시노트10</b> 256GB [SKT] https://search.shopping.naver.com/gate.nhn?id=20552943544
3 삼성 <b>갤럭시노트10</b> 플러스 256GB 공기계-<b>갤럭시노트10</b>플러스 256GB https://search.shopping.naver.com/gate.nhn?id=36758337937
4 [중고]삼성 <b>갤럭시 노트10</b> (256GB) 공기계 무약정 https://search.shopping.naver.com/gate.nhn?id=39080420828
5 자급제통신사공용 삼성 <b>갤럭시 노트10</b>+ 5G 256G C급 https://search.shopping.naver.com/gate.nhn?id=38275466585
6 삼성 <b>갤럭시노트10</b>플러스 <b>GalaxyNote10</b>+ 5G 256G/512G https://search.shopping.naver.com/gate.nhn?id=36881504601
7 <b>갤럭시 노트10</b> 플러스 5G 256GB 공기계-<b>갤럭시노트10</b>플러스 256G https://search.shopping.naver.com/gate.nhn?id=38152829471
8 삼성전자 <b>갤럭시노트10</b> 5G 256GB https://search.shopping.naver.com/gate.nhn?id=85393629281
9 삼성전자 삼성 <b>갤럭시 노트10</b> 256GB 정품 자급제 SM-N970 https://search.shopping.naver.com/gate.nhn?id=36567620602
10 <b>갤럭시 노트10</b> 플러스 5G 256GB 공기계 https://search.shopping.naver.com/gate.nhn?id=38152873354

 

네이버 쇼핑 검색 api 크롤링 활용 하여 엑셀에 넣기

import requests
import openpyxl

client_id = 'xxxxxx' # 본인 네이버 Client ID사용
client_secret = 'xxx' # 본인 Client Secret사용
start, num = 1, 0

excel_file = openpyxl.Workbook()
excel_sheet = excel_file.active
excel_sheet.column_dimensions['B'].width = 100
excel_sheet.column_dimensions['C'].width = 100
excel_sheet.append(['랭킹', '제목', '링크'])

for index in range(10):
    start_number = start + (index * 100)
    naver_open_api = ' https://openapi.naver.com/v1/search/shop.json?query=애플&display=100&start=' + str(start_number)
    header_params = {"X-Naver-Client-Id":client_id, "X-Naver-Client-Secret":client_secret}
    res = requests.get(naver_open_api, headers=header_params)
    if res.status_code == 200:
        data = res.json() # 가져온 데이터를 json 형식으로 변경
        for item in data['items']:
            num += 1
            excel_sheet.append([num, item['title'], item['link']])
    else:
        print ("Error Code:", res.status_code)

excel_file.save('IT.xlsx')
excel_file.close()

결과

공공API 활용하여 대기오염 지수 크롤링

https://www.data.go.kr/data/15073861/openapi.do 에서

활용 신청후 

요청 url 생성

http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty?serviceKey=본인 서비스 키&returnType=json&numOfRows=1&pageNo=1&sidoName=서울&ver=1.0 

{
    "response": {
        "body": {
            "totalCount": 40,
            "items": [
                {
                    "so2Grade": "1",
                    "coFlag": null,
                    "khaiValue": "42",
                    "so2Value": "0.002",
                    "coValue": "0.3",
                    "pm10Flag": null,
                    "o3Grade": "1",
                    "pm10Value": "16",
                    "khaiGrade": "1",
                    "sidoName": "서울",
                    "no2Flag": null,
                    "no2Grade": "1",
                    "o3Flag": null,
                    "so2Flag": null,
                    "dataTime": "2023-04-20 15:00",
                    "coGrade": "1",
                    "no2Value": "0.019",
                    "stationName": "중구",
                    "pm10Grade": "1",
                    "o3Value": "0.025"
                }
            ],
            "pageNo": 1,
            "numOfRows": 1
        },
        "header": {
            "resultMsg": "NORMAL_CODE",
            "resultCode": "00"
        }
    }
}

 

Python 코드로 변환

import requests
import pprint

service_key = 본인 서비스 키
params = '&returnType=json&numOfRows=1&pageNo=1&sidoName=서울&ver=1.0'
open_api = ' http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty?serviceKey=' + service_key + params

res = requests.get(open_api)

pprint.pprint(res.text)

('{"response":{"body":{"totalCount":40,"items":[{"so2Grade":"1","coFlag":null,"khaiValue":"42","so2Value":"0.002","coValue":"0.3","pm25Flag":null,"pm10Flag":null,"o3Grade":"1","pm10Value":"16","khaiGrade":"1","pm25Value":"11","sidoName":"서울","no2Flag":null,"no2Grade":"1","o3Flag":null,"pm25Grade":"1","so2Flag":null,"dataTime":"2023-04-20 '
 '15:00","coGrade":"1","no2Value":"0.019","stationName":"중구","pm10Grade":"1","o3Value":"0.025"}],"pageNo":1,"numOfRows":1},"header":{"resultMsg":"NORMAL_CODE","resultCode":"00"}}}')

 

반응형