본문으로 건너뛰기
KO
API 키 받기

Google Search / Python

Google 검색 결과 Python로 저장하고 CSV로 저장하십시오

Google Search API 요청을 보내 유기 결과 및 수출 타이틀, URLs 및 스니펫 Python의 표준 라이브러리를 읽으십시오.

FlashData · 게시됨

검색 결과 카드는 스프레드 시트로 구성

당신의 환경을 준비

Python 3 및 표준 라이브러리를 사용할 수 있습니다. 제품정보 API 열쇠 귀하의 계정이 유효한 크레딧을 확인합니다. 첫 번째 요청이면 API 퀵스타트.

bash
# Replace YOUR_API_KEY near the top of the code below.

아래 스크립트는 검색에 대한 openai 미국 결과 및 영어 인터페이스를 사용하여 CSV 파일에 반환된 유기 링크가 작성됩니다.

Fetch 및 검색 결과 저장

스크립트를 저장 search.py. 실시간 요청을 제출합니다 source: "google_search" 그리고 읽다 organic 첫 번째 결과에서 배열.

python
import csv
import json
import os
import urllib.request

base_url = "https://data.flashdata.dev"
api_key = "YOUR_API_KEY"
request = urllib.request.Request(
    base_url + "/v1/queries/realtime",
    data=json.dumps({
        "source": "google_search",
        "query": "openai",
        "params": {"gl": "us", "hl": "en", "num": 10},
    }).encode("utf-8"),
    headers={
        "X-API-Key": api_key,
        "Content-Type": "application/json",
    },
    method="POST",
)

with urllib.request.urlopen(request, timeout=60) as response:
    payload = json.load(response)

if payload.get("status") != "done":
    raise RuntimeError(payload.get("message", "Search did not complete"))

results = payload["results"][0].get("organic", [])
with open("google-results.csv", "w", newline="", encoding="utf-8") as output:
    writer = csv.DictWriter(output, fieldnames=["position", "title", "url", "snippet"])
    writer.writeheader()
    for result in results:
        writer.writerow({
            "position": result.get("position", ""),
            "title": result.get("title", ""),
            "url": result.get("link", ""),
            "snippet": result.get("snippet", ""),
        })

print(f"Saved {len(results)} results to google-results.csv")
bash
python3 search.py

열기 google-results.csv 스프레드 시트에서 또는 귀하의 응용 프로그램에로드하십시오. 수출한 란은 위치, 제목, URL 및 스니펫입니다. Python의 CSV 작가는 commas와 선을 위해 인용하고 결과 텍스트 안쪽에 틈새를 취급합니다.

API 응답을 이해하십시오

이 기록 된 응답은 OpenAI 검색에 대해 반환 된 구조를 보여줍니다. 스크립트는 유기 링크 수출; 다른 사용 가능한 섹션은 API 응답에 남아 귀하의 응용 프로그램 필요.

json
{
  "source": "google_search",
  "status": "done",
  "results": [
    {
      "searchParameters": {
        "q": "openai",
        "gl": "us",
        "hl": "en",
        "type": "search",
        "num": 10,
        "page": 1,
        "engine": "google"
      },
      "organic": [
        {
          "title": "OpenAI | Research & Deployment",
          "link": "https://openai.com/",
          "snippet": "We believe our research will eventually lead to artificial general intelligence, a system that can solve human-level problems.",
          "position": 1
        },
        {
          "title": "OpenAI",
          "link": "https://en.wikipedia.org/wiki/OpenAI",
          "snippet": "OpenAI is an American artificial intelligence (AI) public benefit corporation (PBC) headquartered in San Francisco. It develops proprietary generative AI models ...",
          "position": 2
        },
        {
          "title": "OpenAI",
          "link": "https://x.com/OpenAI",
          "snippet": "OpenAI's mission is to ensure that artificial general intelligence benefits all of humanity. can develop research, build financial models, and create ...",
          "position": 3
        },
        {
          "title": "OpenAI",
          "link": "https://www.linkedin.com/company/openai",
          "snippet": "OpenAI is an AI research and deployment company dedicated to ensuring that general-purpose artificial intelligence benefits all of humanity.",
          "position": 4
        },
        {
          "title": "r/OpenAI",
          "link": "https://www.reddit.com/r/OpenAI/",
          "snippet": "OpenAI is an AI research and deployment company. OpenAI's mission is to create safe and powerful AI that benefits all of humanity. OpenAI's ...",
          "position": 5
        }
      ],
      "peopleAlsoAsk": [
        {
          "question": "Is OpenAI created by Elon Musk?"
        },
        {
          "question": "Why are people leaving ChatGPT?"
        },
        {
          "question": "Is OpenAI the same as ChatGPT?"
        },
        {
          "question": "Why is OpenAI in trouble?"
        }
      ],
      "relatedSearches": [
        {
          "query": "OpenAI login"
        },
        {
          "query": "OpenAI chat"
        },
        {
          "query": "OpenAI ChatGPT"
        },
        {
          "query": "OpenAI - wikipedia"
        },
        {
          "query": "OpenAI API"
        },
        {
          "query": "OpenAI app"
        },
        {
          "query": "OpenAI download"
        },
        {
          "query": "OpenAI video"
        }
      ]
    }
  ],
  "usage": {
    "credits": 0.02
  },
  "created_at": "2026-09-16T07:41:40.043Z"
}

의 특징 num 매개 변수 요청 결과 수. Google는 많은 유기 링크가 반환되지 않습니다. 스크립트는 그러나 많은 결과가 반환됩니다.

자주 묻는 질문

변경 query 당신의 주제를 위해, params.gl 국가 및 params.hl 인터페이스 언어에 대한. 제품 정보 params.page 다른 페이지를 요청하려면, 각 페이지는 별도의 API 통화입니다.

시간이 지남에 따라 결과를 비교하려면 쿼리, 지역 및 수집 시간을 각 행에 저장하십시오. API는 검색 스냅 샷을 반환합니다. 역사적인 비교는 저장 스냅 샷에서 온다.