baidu_web/test/test-main.py

79 lines
3.1 KiB
Python

import time
from bs4 import BeautifulSoup
from playwright.sync_api import sync_playwright
import json, re
# 헤더 설정
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Language": "en-US,en;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"DNT": "1", # Do Not Track
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Cache-Control": "max-age=0"
}
# Playwright 사용
with sync_playwright() as p:
# 브라우저 실행
browser = p.chromium.launch(headless=False)
page = browser.new_page()
# 헤더 설정
page.set_extra_http_headers(headers)
# 웹사이트 접속
url = "https://graph.baidu.com/s?card_key=&entrance=GENERAL&extUiData%5BisLogoShow%5D=1&f=all&isLogoShow=1&session_id=&sign=126316b6a2b0c27d34c5c01731123409&tpl_from=pc"
page.goto(url)
# 이미지 업로드 버튼 클릭
upload_button_xpath = '//*[@id="app"]/div/div[1]/div/div[1]/div/div/div[1]/span[1]/span[1]'
page.click(upload_button_xpath)
time.sleep(1)
# 로컬 이미지 업로드
image_upload_xpath = '//*[@id="app"]/div/div[1]/div/div[1]/div/div/div[1]/div/div[2]/div[2]/div/form/input'
page.set_input_files(image_upload_xpath, "1.png")
time.sleep(5) # 업로드 및 검색 결과 로드 대기
# 검색 결과 페이지에서 JSON 데이터 추출
content = page.content()
soup = BeautifulSoup(content, 'html.parser')
# JSON 데이터가 포함된 스크립트 태그 추출
script_tag = soup.select_one("html > head > script:nth-of-type(2)")
if script_tag:
# 불필요한 부분 제거
raw_data = script_tag.string.strip()
# window.cardData = 뒤에 있는 JSON 데이터만 추출
match = re.search(r"window\.cardData\s*=\s*(\[\{.*\}\]);", raw_data, re.DOTALL)
if match:
json_data_str = match.group(1) # JSON 데이터만 추출
try:
# JSON으로 변환
data = json.loads(json_data_str)
# 필요한 데이터 추출 및 출력
for card in data:
if card.get("cardName") == "product":
products = card["tplData"]["list"]
for product in products:
title = product.get("desc", "")
source = product.get("source", "")
price = product.get("text", "")
buyurl = product.get("buyurl", "")
print(f"상품명: {title}, 출처: {source}, 가격: {price}, 구매 링크: {buyurl}")
except json.JSONDecodeError as e:
print("JSON 디코딩 오류:", e)
else:
print("JSON 데이터를 찾을 수 없습니다.")
else:
print("JSON 데이터가 포함된 스크립트를 찾지 못했습니다.")
# 브라우저 종료
browser.close()