python으로 네이버 사설 크롤링하기 2

moon-dad·2024년 2월 16일

크롤링된 데이터를 매일 아침 메신저로 발송해 봅니다.
2편 에서는 1을 조금 보완하여 단축URL 을 넣는 것으로 기존 소스를 수정하고
3편 에서는 텔레그램을 통해 발송해 보겠습니다.

단축URL 생성
네이버 단축URL로 생성해 봅니다. 미리 개발자센터에 등록해서 Client-Id와 Client-Secret를 발급 받아야 합니다.
단축URL API는 다음과 같습니다.
https://developers.naver.com/docs/utils/shortenurl/

cURL을 사용해서 아래와 같이 요청합니다.

curl "https://openapi.naver.com/v1/util/shorturl" \
    -d "url=http://d2.naver.com/helloworld/4874130" \
    -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" \
    -H "X-Naver-Client-Id: {애플리케이션 등록 시 발급받은 클라이언트 아이디 값}" \
    -H "X-Naver-Client-Secret: {애플리케이션 등록 시 발급받은 클라이언트 시크릿 값}" -v

Python 에서는 requests를 사용하여 호출 했습니다.

import requests
# Client-Id, Client-Secret 는 setting에 저장
from setting import naver

def naverShortenUrl(orignUrl):
    url = "https://openapi.naver.com/v1/util/shorturl"
    headers = {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "X-Naver-Client-Id": naver['client_id'],
        "X-Naver-Client-Secret": naver['client_secret']
    }
    data = { "url": orignUrl }

    response = requests.post(url, headers=headers, data=data)
    jsonData = response.json()

    return jsonData['result']['url']

print(naverShortenUrl('https://n.news.naver.com/mnews/article/469/0000785479?sid=110'))

setting.py

naver = {
    'client_id':'P_*************pzW',
    'client_secret':'B***********h',
}
profile
나는 아무것도 아닙니다.

0개의 댓글