-
[n8n] Converting Google News URLs to Source URLs컴퓨터 2024. 12. 20. 15:49
구글 뉴스 검색을 하면 기본적으로 Source URL(origin URL)이 아닌 구글을 통해(리다이렉션) 넘어가는 URL이 나옴
문제는 n8n에서 뉴스 컨텐츠를 가져오고 싶으면 HTTP Request 혹은 Puppeteer 를 사용해야 하는데 테스트 결과 가끔 컨텐츠를 못가져오는 상황이 발생한다.
그래서 n8n으로 뉴스 스크랩을 하고, 1차 적으로 google news URL을 Source(Origin) URL로 바꾸는 방법이다.
python package가 있는데 n8n에서 js와 python을 실행할 순 있지만 외부 라이브러리 설치는 불가한 상황.
https://github.com/SSujitX/google-news-url-decoder/tree/main
GitHub - SSujitX/google-news-url-decoder: A Python script to decode Google News article URLs.
A Python script to decode Google News article URLs. - SSujitX/google-news-url-decoder
github.com
1. FastAPI, uvicorn, googlenewsdecoder 설치
pip install fastapi uvicorn googlenewsdecoder
2. API 사용을 위한 코드 구현
인증은 간단하게 내부에서만 접근할 수 있도록 IP 설정.
만약 접근이 안되면 서버에서
sudo ufw allow 5000 # 방화벽 설정 hostname -I # 서버 IP들 확인
from fastapi import FastAPI, Request, HTTPException from pydantic import BaseModel from googlenewsdecoder import new_decoderv1 class DecodeRequest(BaseModel): source_url: str interval_time: int = 5 app = FastAPI() ALLOWED_IPS = {"127.0.0.1"} # 여기에 IP 추가 @app.middleware("http") async def ip_filter_middleware(request: Request, call_next): client_ip = request.client.host print("client ip:", client_ip); if client_ip not in ALLOWED_IPS: raise HTTPException(status_code=403, detail="Access forbidden: Your IP address is not allowed.") response = await call_next(request) return response @app.post("/decode_org/") async def decode_url(request: DecodeRequest): try: decoded_url = new_decoderv1(request.source_url, interval=request.interval_time) if decoded_url.get("status"): return {"decoded_url": decoded_url["decoded_url"]} else: raise HTTPException(status_code=400, detail=decoded_url["message"]) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.post("/decode/") async def decode_url(request: DecodeRequest): try: print(f"Source URL: {request.source_url}, Interval: {request.interval_time}") decoded_url = new_decoderv1(request.source_url, interval=request.interval_time) if decoded_url.get("status"): return {"decoded_url": decoded_url["decoded_url"]} else: raise HTTPException(status_code=400, detail=decoded_url["message"]) except Exception as e: print(f"Error: {e}") raise HTTPException(status_code=500, detail=str(e))
3. 실행 및 테스트
서버 실행
uvicorn your_fastapi_app:app --host 0.0.0.0 --port 5000
curl 테스트
curl -X POST "http://127.0.0.1:5000/decode/" \ -H "accept: application/json" \ -H "Content-Type: application/json" \ -d '{ "source_url": "https://news.google.com/---", #CHANGE HERE "interval_time": 5 }'
잘 된다면 systemd로 등록하자.
4. systemd 등록 및 시작
sudo vi /etc/systemd/system/uvicorn_app.service [Unit] Description=Uvicorn FastAPI App After=network.target [Service] User=n8n #Change user WorkingDirectory=/home/n8n/google_decoder #Change your working directory ExecStart=/home/n8n/.local/bin/uvicorn main:app --host 0.0.0.0 --port 5000 Restart=always [Install] WantedBy=multi-user.target
# systemd 리로드 및 재시작 sudo systemctl daemon-reload sudo systemctl restart uvicorn_app # 상태 확인 sudo systemctl status uvicorn_app
5. n8n HTTP Request 등록
n8n HTTP Request에 위 test했던 curl을 import 하면 된다. ip는 바꿔서.
끝.