Chuyển đến nội dung
VI
Lấy khóa API

Google Search / Python

Được Google Kết quả tìm kiếm Python Và cứu họ CSV

Gửi a Google Search API yêu cầu, đọc kết quả hữu cơ và tiêu đề xuất khẩu, URLs và trích đoạn với PythonThư viện thông thường của họ.

FlashData · Xuất bản

Name

Chuẩn bị môi trường

Anh sẽ dùng Python 3 và thư viện thông thường của nó. Tạo ra một Phím API và đảm bảo tài khoản của bạn có sẵn tín dụng. Nếu đây là yêu cầu đầu tiên của bạn, xem API khởi chạy nhanh.

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

Văn lệnh bên dưới tìm kiếm openai bằng cách sử dụng kết quả Mỹ và một giao diện tiếng Anh, sau đó viết các liên kết hữu cơ trở lại đến a CSV Hồ sơ.

Lấy và lưu kết quả tìm kiếm

Lưu văn lệnh dạng search.py. Nó gửi đến một yêu cầu thời gian thực với source: "google_search" và đọc organic Sắp xếp từ kết quả đầu tiên.

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

Mở google-results.csv trong bảng tính hoặc nạp nó vào ứng dụng của bạn. Các cột xuất khẩu là vị trí, tiêu đề, URL và mảnh vụn. Python’ CSV tác giả trích dẫn những dấu phẩy và đường đứt đoạn bên trong kết quả.

Hiểu phản ứng của API

Câu trả lời được ghi lại này cho thấy cấu trúc được trả lại để tìm kiếm OpenAI. Các tập lệnh xuất khẩu các liên kết hữu cơ; các phần khác còn lại trong API Nếu đơn của bạn cần thì hãy trả lời.

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"
}

Hạt num số lượng tham số yêu cầu kết quả. Nó không đảm bảo rằng Google sẽ trả lại rất nhiều liên kết hữu cơ. Văn lệnh tiết kiệm được bao nhiêu kết quả đã được trả lại.

Thay đổi tìm kiếm

Thay đổi query Cho chủ đề của bạn, params.gl cho đất nước và params.hl cho ngôn ngữ giao diện. Dùng params.page yêu cầu trang khác; mỗi trang là riêng biệt API Gọi đi.

Để so sánh kết quả theo thời gian, hãy lưu lại các câu hỏi, vùng và khoản thời gian thu thập bên cạnh mỗi hàng. Hạt API là một hình ảnh tìm kiếm; sự so sánh lịch sử đến từ những bức ảnh bạn lưu.