mirror of
https://github.com/j93es/browser-use-oauth.git
synced 2026-06-04 12:41:53 +09:00
feat/refect 가져오기
This commit is contained in:
commit
54682cdb72
43 changed files with 702 additions and 520 deletions
|
|
@ -1,3 +0,0 @@
|
|||
from lib.llm.create import *
|
||||
|
||||
from lib.llm.prompt import *
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
from langchain.callbacks.base import BaseCallbackHandler
|
||||
from langchain_google_genai import ChatGoogleGenerativeAI
|
||||
|
||||
class QuotaExhaustedHandler(BaseCallbackHandler):
|
||||
def on_llm_error(self, error, **kwargs):
|
||||
if "ResourceExhausted" in str(error) or "429" in str(error):
|
||||
print("⚠️ API 쿼터가 소진되었습니다. 재시도 로직에 위임합니다...")
|
||||
# backoff handled in scan_one_url
|
||||
|
||||
def CreateChatGoogleGenerativeAI(model: str):
|
||||
"""재시도 로직이 포함된 LLM 생성"""
|
||||
if model == "fallback":
|
||||
print("⚠️ Fallback 모델을 사용합니다. Envorinment 변수를 확인하세요.")
|
||||
print("⚠️ Model Gemini-2.0-flash-lite를 사용합니다.")
|
||||
model = "gemini-2.0-flash-lite"
|
||||
return ChatGoogleGenerativeAI(
|
||||
model=model,
|
||||
max_retries=10, # 최대 재시도 횟수 증가
|
||||
model_kwargs={
|
||||
"request_timeout": 120, # 타임아웃 시간 증가 (2분)
|
||||
},
|
||||
callbacks=[QuotaExhaustedHandler()],
|
||||
# API 호출 간격 조정
|
||||
temperature=0.0,
|
||||
)
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
# Extended planner prompt
|
||||
extend_planner_system_message = f"""
|
||||
|
||||
# 목적 : Microsoft OAuth 로그인
|
||||
|
||||
## ✅ Step 1 : Step 3에서
|
||||
|
||||
만약에 Microsoft에 로그인 되어 있는 계정(oauth test)가 없을 경우
|
||||
- Microosoft.sensitive.json에서 sign in with your username(email) x_username and password is x_password
|
||||
- 반드시 이 과정에서 username을 먼저 입력하고 다음 과정에서 암호 사용을 누른 후 password를 입력해야 한다.
|
||||
|
||||
|
||||
쿠키 삭제 방법:
|
||||
chrome://settings/clearBrowserData에 들어가서 삭제해주세요.
|
||||
|
||||
🛑 절대 아래와 같이 해석하지 말 것:
|
||||
- ❌ 버튼 클릭 후 페이지 로딩만 기다리고 돌아가기
|
||||
- ❌ URL 저장 없이 go_back() 호출
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
### ✨ 추가 안전 장치: "뒤로가기(go_back) 호출 조건" 제한
|
||||
|
||||
```text
|
||||
🛑 뒤로가기(go_back)은 다음 조건이 모두 충족될 때만 사용 => 다만 로그인 실패 시, 뒤로가기 수행:
|
||||
- ✅ 로그인 흐름이 완료됨 (예: redirect back to app, or callback URL)
|
||||
- ✅ 현재 리디렉션 URL이 수집됨
|
||||
- ✅ 결과에 저장 후 다음 버튼 탐색을 위해 복귀 필요할 때
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚫 Step 2: 버튼 없음 또는 예외 발생 시
|
||||
|
||||
* 유효한 SSO 버튼이 **전혀 없을 경우**
|
||||
* 예외, 오류 등 발생 시
|
||||
|
||||
-> 즉시 중단
|
||||
|
||||
---
|
||||
|
||||
## 📎 중요 규칙 요약
|
||||
|
||||
* 🔁 단계는 반드시 순서대로 진행
|
||||
* 🔐 로그인은 쿠키/세션으로 유지된 상태에서 수행
|
||||
* 👀 직접 OAuth Providor ID/PW를 입력하여도 됨 가지고 있다면
|
||||
* ⛔ 추측한 URL은 접속하지 않음
|
||||
|
||||
---
|
||||
"""
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
# @file purpose: This file contains the prompt for extracting a list of OAuth providers from a web page.
|
||||
# OAuth 리스트 추출용 프롬프트 (클릭하지 않고 단순 식별만)
|
||||
extract_oauth_list_prompt = f"""
|
||||
🎯 목적: 주어진 초기 URL 내에서 **OAuth 로그인 Provider**를 찾아 아래 형식의 JSON으로 정리합니다.
|
||||
|
||||
📌 작업 목표:
|
||||
- Google, GitHub, Discord, Facebook, Apple, Microsoft, Twitter, LinkedIn 등 **OAuth 인증을 사용하는 외부 로그인 링크**에서 Provider 이름만 모두 수집합니다.
|
||||
- 로그인 버튼, 링크 클릭 등을 통해 탐색을 진행할 수 있습니다.
|
||||
- **같은 provider가 여러 번 나와도 하나만 저장**합니다.
|
||||
|
||||
🛑 제한 사항:
|
||||
- ❌ 로그인 입력창이나 이메일/비밀번호 입력 방식은 제외합니다.
|
||||
- ❌ 검색 엔진, 사이트 외부 탐색은 금지합니다.
|
||||
- ❌ URL 추측이나 직접 입력은 금지합니다.
|
||||
- ❌ OAuth가 없는 경우 빈 배열 `[]`로 반환합니다.
|
||||
- ❌ OAuth가 아닌 일반 로그인은 무시합니다.
|
||||
|
||||
🔍 탐색 방법:
|
||||
1. 초기 URL에 접속하여 **클라이언트용 로그인 페이지**로 진입합니다.
|
||||
2. 페이지가 정상적으로 로드되었다고 가정합니다.
|
||||
3. 'Continue with X', 'Continue with Google'... 등의 버튼이나 링크를 식별합니다.
|
||||
|
||||
|
||||
🧾 출력 형식 (예시):
|
||||
|
||||
```json
|
||||
{{
|
||||
"oauth_providers": [
|
||||
"Google",
|
||||
"GitHub",
|
||||
"Discord"
|
||||
]
|
||||
}}
|
||||
```
|
||||
|
||||
📌 주의:
|
||||
결과가 없는 경우 빈 배열 `[]`로 반환합니다.
|
||||
정확한 provider 이름을 포함해 주세요.
|
||||
|
||||
"""
|
||||
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
# Extended planner prompt
|
||||
extend_planner_system_message = f"""
|
||||
🎯 목적: 웹 자동화를 위한 **SSO 로그인 리디렉션 URL 수집**
|
||||
|
||||
📌 주의사항 (전제 조건)
|
||||
- ❌ **검색 엔진(Google, Bing 등) 사용 금지**
|
||||
- ✅ **초기 제공된 URL 내에서만 탐색**
|
||||
- ❌ 직접 이동하거나 추측한 링크 클릭 금지
|
||||
- ⛔ 추측한 URL은 대답하거나 클릭하지 마세요
|
||||
- OAuth가 아닌 일반 로그인은 무시
|
||||
- OAuth가 없다면 **즉시 중단**하고 빈 배열 반환
|
||||
|
||||
---
|
||||
|
||||
## 🧩 Step 0: 페이지 차단(Block) 여부 확인
|
||||
|
||||
초기 URL의 로그인 페이지에 접근하여 다음 사항을 점검합니다:
|
||||
|
||||
- 🚫 페이지 차단됨 (Firewall, Access Denied 등) → 즉시 중단
|
||||
- 🔒 CAPTCHA는 통과 가능 (해결하고 계속 진행)
|
||||
- ❗ 로그인 UI가 정상적으로 로드되지 않으면 중단
|
||||
|
||||
📤 차단 시 즉시 종료
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Step 1: 로그인 페이지 탐색
|
||||
|
||||
* 초기 URL에 접속하여 **클라이언트용 로그인 페이지**로 진입합니다.
|
||||
* 쿠키 동의, 개인정보 안내 등 팝업은 무시하거나 닫고 계속 진행하세요.
|
||||
* 페이지가 정상 로드되었다고 가정합니다.
|
||||
|
||||
---
|
||||
|
||||
## 👀 Step 2: SSO 로그인 버튼 식별
|
||||
|
||||
아래 **OAuth SSO 버튼들만** 유효합니다:
|
||||
|
||||
* ✅ Google, GitHub, Facebook, LinkedIn, Microsoft, Naver
|
||||
|
||||
**유효한 버튼 기준**:
|
||||
|
||||
* OAuth 인증 흐름을 실제로 트리거
|
||||
* `window.location` 또는 `<a href=...>` 또는 JS로 redirect가 발생
|
||||
|
||||
**제외 버튼들 (클릭 금지)**:
|
||||
|
||||
* ❌ 일반 로그인, 패스키, 이메일/전화번호, 인증서 기반, 비밀번호 입력
|
||||
|
||||
---
|
||||
|
||||
## ✅ Step 3: 모든 SSO 버튼 클릭 및 로그인 시도
|
||||
|
||||
> 각 SSO 로그인 버튼을 클릭한 뒤 반드시 아래 절차를 **완전히 수행**해야 합니다.
|
||||
|
||||
각 SSO 버튼에 대해 다음을 수행:
|
||||
|
||||
1. 버튼 클릭
|
||||
2. ✅ 로그인 진행:
|
||||
- 로그인 페이지에서 OAuth 인증을 완료합니다.
|
||||
- sign in with your username(email) x_username and password is x_password
|
||||
- 버튼같은게 안눌리면 새로고침을 해봐
|
||||
- **로그인 완료 후 authorize 등 버튼이 있으면 클릭**
|
||||
- GitHub같은 경우 Authorize 버튼이 뜨는데 오래걸릴 수 있음, 기다려야 할 수도 있음
|
||||
- 만약 버튼을 눌러도 반응이 없을 경우 새로고침을 한번 해주세요.
|
||||
- **OAuth Flow가 완료되면 (callback URL 도달 또는 인증 완료) 즉시 작업 종료**
|
||||
4. 로그인이 성공하면 모두 쿠키를 삭제하고 다음 SSO 버튼을 클릭합니다.
|
||||
5. 다음 SSO 버튼으로 반복 진행
|
||||
|
||||
쿠키 삭제 방법:
|
||||
chrome://settings/clearBrowserData에 들어가서 삭제해주세요.
|
||||
|
||||
🛑 절대 아래와 같이 해석하지 말 것:
|
||||
- ❌ 버튼 클릭 후 페이지 로딩만 기다리고 돌아가기
|
||||
- ❌ URL 저장 없이 go_back() 호출
|
||||
|
||||
---
|
||||
|
||||
### ✨ 추가 안전 장치: "뒤로가기(go_back) 호출 조건" 제한
|
||||
|
||||
```text
|
||||
🛑 뒤로가기(go_back)은 다음 조건이 모두 충족될 때만 사용 => 다만 로그인 실패 시, 뒤로가기 수행:
|
||||
- ✅ 로그인 흐름이 완료됨 (예: redirect back to app, or callback URL)
|
||||
- ✅ 현재 리디렉션 URL이 수집됨
|
||||
- ✅ 결과에 저장 후 다음 버튼 탐색을 위해 복귀 필요할 때
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚫 Step 4: 버튼 없음 또는 예외 발생 시
|
||||
|
||||
* 유효한 SSO 버튼이 **전혀 없을 경우**
|
||||
* 예외, 오류 등 발생 시
|
||||
|
||||
-> 즉시 중단
|
||||
|
||||
---
|
||||
|
||||
## 📎 중요 규칙 요약
|
||||
|
||||
* ✅ **모든 SSO 로그인은 반드시 실행** (가능한 버튼은 모두 클릭)
|
||||
* 🔁 단계는 반드시 순서대로 진행
|
||||
* 🔐 로그인은 쿠키/세션으로 유지된 상태에서 수행
|
||||
* 👀 직접 OAuth Providor ID/PW를 입력하여도 됨 가지고 있다면
|
||||
* ⛔ 추측한 URL은 접속하지 않음
|
||||
|
||||
---
|
||||
"""
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
# export from show_info
|
||||
|
||||
from lib.utils.agent_info import *
|
||||
from lib.utils.backend_client import *
|
||||
from lib.utils.config import *
|
||||
from lib.utils.is_html import *
|
||||
from lib.utils.logger import *
|
||||
from lib.utils.read_txt import *
|
||||
|
||||
from lib.utils.browser_use import *
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
from lib.utils.config import (
|
||||
BACKEND_URL,
|
||||
GOOGLE_API_KEY,
|
||||
GOOGLE_MODEL,
|
||||
GOOGLE_PLANNER_MODEL,
|
||||
)
|
||||
|
||||
|
||||
def show_info():
|
||||
print("🔧 환경 설정:")
|
||||
print(browser_use_version())
|
||||
print(f"🔗 Backend URL: {BACKEND_URL}")
|
||||
print(
|
||||
f"🔑 Google API Key: {'*' * (len(GOOGLE_API_KEY) - 4) + GOOGLE_API_KEY[-4:] if GOOGLE_API_KEY else None}"
|
||||
)
|
||||
print(f"🌐 Google Model: {GOOGLE_MODEL}")
|
||||
print(f"🌐 Google Planner Model: {GOOGLE_PLANNER_MODEL}")
|
||||
|
||||
|
||||
def browser_use_version():
|
||||
try:
|
||||
# run uv pip show browser-use
|
||||
import subprocess
|
||||
|
||||
result = subprocess.run(
|
||||
["uv", "pip", "show", "browser-use"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
|
||||
print("📦 Browser Use 패키지 정보:")
|
||||
return result.stdout.strip()
|
||||
except ImportError:
|
||||
return None
|
||||
|
||||
|
||||
def env_cheker():
|
||||
if GOOGLE_API_KEY is None:
|
||||
raise ValueError("GOOGLE_API_KEY 환경변수가 설정되지 않았습니다.")
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
import requests
|
||||
|
||||
from lib.utils.config import BACKEND_URL
|
||||
|
||||
def notify_backend(target_url):
|
||||
# Backend에 스캔 시작을 알림
|
||||
try:
|
||||
response = requests.post(
|
||||
f"{BACKEND_URL}/start", params={"url": target_url}, timeout=5
|
||||
)
|
||||
if response.status_code == 200:
|
||||
print(f"✅ Backend notified: {response.text}")
|
||||
else:
|
||||
print(f"⚠️ Backend notification failed: {response.status_code}")
|
||||
except requests.exceptions.ConnectionError:
|
||||
print(
|
||||
f"⚠️ Backend server not available at {BACKEND_URL}. Continuing without notification."
|
||||
)
|
||||
except requests.exceptions.Timeout:
|
||||
print(f"⚠️ Backend notification timed out. Continuing without notification.")
|
||||
except Exception as e:
|
||||
print(f"⚠️ Failed to notify backend: {e}")
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
from lib.utils.browser_use.clean_resources import *
|
||||
from lib.utils.browser_use.func import *
|
||||
from lib.utils.browser_use.model import *
|
||||
from lib.utils.browser_use.init_profile import *
|
||||
from lib.utils.browser_use.sensitive_data import *
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
from pathlib import Path
|
||||
|
||||
async def clean_resources(agent=None, session=None):
|
||||
"""리소스를 정리하는 함수"""
|
||||
storage_state_temp_path = Path("./data/storage_state_temp.json").resolve()
|
||||
if storage_state_temp_path.exists():
|
||||
try:
|
||||
# remove file
|
||||
print(f"🗑️ 임시 스토리지 상태 파일 삭제 중: {storage_state_temp_path}")
|
||||
# unlink removes the file
|
||||
storage_state_temp_path.unlink()
|
||||
print("🗑️ 임시 스토리지 상태 파일 삭제 완료.")
|
||||
except Exception as e:
|
||||
print(f"⚠️ 임시 스토리지 상태 파일 삭제 실패: {e}")
|
||||
|
||||
if agent:
|
||||
try:
|
||||
await agent.close()
|
||||
except Exception as e:
|
||||
print(f"⚠️ 에이전트 리소스 정리 실패: {e}")
|
||||
if session:
|
||||
try:
|
||||
await session.close()
|
||||
except Exception as e:
|
||||
print(f"⚠️ 세션 리소스 정리 실패: {e}")
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
import os
|
||||
import json
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
from browser_use import BrowserProfile
|
||||
import json
|
||||
import os
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv(override=True)
|
||||
|
||||
async def setup_storage_state():
|
||||
"""Setup browser storage state for session persistence."""
|
||||
# Get the script directory to ensure correct path resolution
|
||||
script_dir = Path(__file__).parent.parent.parent.parent
|
||||
storage_state_path = script_dir / "data" / "storage_state.json"
|
||||
storage_state_temp_path = script_dir / "data" / "storage_state_temp.json"
|
||||
|
||||
print(f"📂 Storage state path: {storage_state_path}")
|
||||
print(f"📂 Temp storage state path: {storage_state_temp_path}")
|
||||
|
||||
if storage_state_path.exists():
|
||||
try:
|
||||
if storage_state_temp_path.exists():
|
||||
storage_state_temp_path.unlink()
|
||||
|
||||
with open(storage_state_path, 'r') as f:
|
||||
storage_data = json.load(f)
|
||||
|
||||
with open(storage_state_temp_path, 'w') as f:
|
||||
json.dump(storage_data, f, indent=4)
|
||||
|
||||
print(f"🔄 Using existing storage state: {storage_state_temp_path}")
|
||||
return str(storage_state_temp_path)
|
||||
|
||||
except Exception as e:
|
||||
print(f"⚠️ Error processing storage state: {e}")
|
||||
if storage_state_temp_path.exists():
|
||||
storage_state_temp_path.unlink()
|
||||
return None
|
||||
|
||||
print("⚠️ No existing storage state found")
|
||||
return None
|
||||
|
||||
|
||||
def setup_proxy():
|
||||
"""Configure proxy settings from environment variables."""
|
||||
proxy_host = os.getenv("PROXY_HOST")
|
||||
proxy_port = os.getenv("PROXY_PORT")
|
||||
|
||||
if proxy_host and proxy_port:
|
||||
proxy_url = f"http://{proxy_host}:{proxy_port}"
|
||||
print(f"🔗 Using proxy: {proxy_host}:{proxy_port}")
|
||||
return proxy_url
|
||||
else:
|
||||
print("🔗 No proxy configured, using direct connection.")
|
||||
return None
|
||||
|
||||
|
||||
def get_browser_args():
|
||||
"""Get browser arguments for enhanced compatibility and security."""
|
||||
return [
|
||||
# Security and isolation
|
||||
"--disable-web-security",
|
||||
"--disable-site-isolation-trials",
|
||||
"--disable-features=IsolateOrigins,site-per-process",
|
||||
"--ignore-certificate-errors",
|
||||
"--ignore-ssl-errors",
|
||||
"--allow-running-insecure-content",
|
||||
# Performance and rendering
|
||||
"--disable-features=VizDisplayCompositor",
|
||||
"--disable-dev-shm-usage",
|
||||
# Popup and automation
|
||||
"--disable-popup-blocking",
|
||||
"--disable-blink-features=AutomationControlled",
|
||||
# Browser behavior
|
||||
"--no-first-run",
|
||||
"--no-service-autorun",
|
||||
"--no-default-browser-check",
|
||||
"--password-store=basic",
|
||||
"--use-mock-keychain",
|
||||
# Extensions
|
||||
"--disable-extensions-file-access-check",
|
||||
"--disable-extensions-http-throttling",
|
||||
"--disable-component-extensions-with-background-pages",
|
||||
# Language
|
||||
f"--lang={os.getenv('LANG', 'en_US')}",
|
||||
]
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
import os
|
||||
from lib.utils.browser_use.func import *
|
||||
|
||||
# Initialize configuration
|
||||
proxy_url = setup_proxy()
|
||||
|
||||
async def GetProfile():
|
||||
storage_state_path = await setup_storage_state()
|
||||
|
||||
# Handle potential encoding issues with storage state file
|
||||
try:
|
||||
if storage_state_path and os.path.exists(storage_state_path):
|
||||
# Test if file can be read properly, if not, skip it
|
||||
with open(storage_state_path, 'r', encoding='utf-8') as f:
|
||||
f.read()
|
||||
storage_state = storage_state_path
|
||||
else:
|
||||
print("⚠️ Storage state file not found or inaccessible, proceeding without it.")
|
||||
storage_state = None
|
||||
except (UnicodeDecodeError, FileNotFoundError):
|
||||
# If there's an encoding error, don't use the storage state
|
||||
storage_state = None
|
||||
|
||||
profile = BrowserProfile(
|
||||
# Security settings
|
||||
disable_security=True,
|
||||
stealth=True,
|
||||
|
||||
# Display settings
|
||||
headless=False,
|
||||
device_scale_factor=1,
|
||||
window_size={"width": 1600, "height": 900},
|
||||
viewport={"width": 1600, "height": 900},
|
||||
|
||||
# Data persistence
|
||||
user_data_dir=None,
|
||||
storage_state=storage_state,
|
||||
|
||||
# Network settings
|
||||
proxy={"server": proxy_url} if proxy_url else None,
|
||||
|
||||
# Additional arguments
|
||||
args=get_browser_args(),
|
||||
)
|
||||
|
||||
return profile
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
from typing import List
|
||||
from pydantic import BaseModel
|
||||
|
||||
# 출력 모델
|
||||
class OAuth(BaseModel):
|
||||
provider: str
|
||||
oauth_uri: str = "" # OAuth 리스트 추출 단계에서는 URI가 없을 수 있음
|
||||
|
||||
|
||||
class OAuthList(BaseModel):
|
||||
oauth_providers: List[str] # 이제 문자열 배열로 변경
|
||||
|
||||
|
||||
# 기존 모델 유지 (backward compatibility)
|
||||
BaseModel = OAuthList
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
# read json file .sensitive.json
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
def GetSensitiveData():
|
||||
"""
|
||||
Reads sensitive data from a .sensitive.json file in the current directory.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the sensitive data.
|
||||
"""
|
||||
file_path = os.path.join(os.getcwd(), '.sensitive.json')
|
||||
|
||||
if not os.path.exists(file_path):
|
||||
return None
|
||||
|
||||
with open(file_path, 'r') as file:
|
||||
sensitive_data = json.load(file)
|
||||
|
||||
return sensitive_data
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
import os
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv(verbose=True, override=True)
|
||||
|
||||
BACKEND_URL = os.getenv("BACKEND_URL", "http://localhost:11081")
|
||||
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
||||
GOOGLE_MODEL = os.getenv("GOOGLE_MODEL", "gemini-2.5-flash-preview-05-20")
|
||||
GOOGLE_PLANNER_MODEL = os.getenv("GOOGLE_PLANNER_MODEL", "gemini-2.5-pro-preview-06-05")
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
import requests
|
||||
|
||||
def is_html_url(url: str, timeout: float = 10.0) -> bool:
|
||||
"""
|
||||
주어진 URL에 HEAD 요청을 보내고, 응답 헤더의 Content-Type이 HTML인지 확인합니다.
|
||||
- url: 검사할 URL 문자열
|
||||
- timeout: 요청 타임아웃(초 단위)
|
||||
|
||||
반환값:
|
||||
- Content-Type이 'text/html' 로 시작하면 True, 그렇지 않으면 False
|
||||
"""
|
||||
|
||||
try:
|
||||
with requests.get(url, timeout=timeout, stream=True) as response:
|
||||
# 응답 코드가 200번대가 아니면 False로 간주
|
||||
if not response.ok:
|
||||
return False
|
||||
|
||||
content_type = response.headers.get('Content-Type', '')
|
||||
# Content-Type에 'text/html'이 포함되어 있으면 HTML로 간주
|
||||
return content_type.lower().startswith('text/html')
|
||||
except requests.RequestException:
|
||||
return False
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_urls = [
|
||||
'https://www.example.com',
|
||||
'https://api.github.com', # JSON API라서 HTML이 아닐 확률이 높음
|
||||
'https://raw.githubusercontent.com' # 텍스트 파일 등 다양한 타입
|
||||
]
|
||||
|
||||
for url in test_urls:
|
||||
if is_html_url(url):
|
||||
print(f"[HTML] {url}")
|
||||
else:
|
||||
print(f"[Not HTML] {url}")
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
# 미리 정해진 파일 경로
|
||||
FILE_PATH = Path("data/log.txt")
|
||||
|
||||
def logger(msg: str) -> None:
|
||||
try:
|
||||
"""
|
||||
msg 문자열을 파일 끝에 추가합니다.
|
||||
- 파일이 없으면 새로 생성
|
||||
- 디렉터리가 없으면 생성
|
||||
"""
|
||||
# 상위 디렉터리 생성 (이미 있으면 무시)
|
||||
FILE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 현재 시각 구해서 포맷팅
|
||||
now = datetime.now()
|
||||
timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# 메시지에 개행이 없으면 자동으로 붙이기
|
||||
newline = "" if msg.endswith("\n") else "\n"
|
||||
line = f"[{timestamp}] {msg}{newline}"
|
||||
|
||||
# 'a' 모드: 파일이 없으면 생성, 있으면 이어쓰기
|
||||
with FILE_PATH.open(mode="a", encoding="utf-8") as f:
|
||||
f.write(line)
|
||||
except:
|
||||
print(msg)
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
def read_lines_between(filepath: str, start_line: int, end_line: int) -> list[str]:
|
||||
"""
|
||||
파일에서 start_line번 째 줄부터 end_line번 째 줄까지 읽어와
|
||||
각 줄을 요소로 갖는 리스트를 반환하는 함수.
|
||||
|
||||
Parameters:
|
||||
----------
|
||||
filepath : str
|
||||
읽을 텍스트 파일의 경로
|
||||
start_line : int
|
||||
읽기 시작할 행 번호 (1부터 시작)
|
||||
end_line : int
|
||||
읽을 마지막 행 번호 (start_line <= end_line)
|
||||
|
||||
Returns:
|
||||
-------
|
||||
list[str]
|
||||
각 줄을 문자열로 저장한 리스트.
|
||||
파일에 해당 범위의 줄이 없으면 가능한 만큼만 반환.
|
||||
"""
|
||||
|
||||
if start_line < 1 or end_line < start_line:
|
||||
raise ValueError("start_line은 1 이상이어야 하며, end_line은 start_line 이상이어야 합니다.")
|
||||
|
||||
selected_lines: list[str] = []
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
for idx, line in enumerate(f, start=1):
|
||||
if idx < start_line:
|
||||
# 아직 읽기 시작 전
|
||||
continue
|
||||
if idx > end_line:
|
||||
# 읽을 범위를 벗어났으므로 중단
|
||||
break
|
||||
# 줄 끝의 개행 문자를 제거하고 리스트에 추가
|
||||
selected_lines.append(line.rstrip('\n'))
|
||||
return selected_lines
|
||||
Loading…
Add table
Add a link
Reference in a new issue