谷歌搜索API使用 demo

谷歌search api 使用

  • demo代码如下

    import requests
    import json
    
    def google_search(query, api_key, cx):
        url = ""
        params = {
            "q": query,
            "key": api_key,
            "cx": cx
        }
        response = requests.get(url, params=params)
        return response.json()
    
    # 将以下值替换为您的API密钥和搜索引擎ID
    API_KEY = "XXXX"
    SEARCH_ENGINE_ID = "XXXX"
    
    query = "OpenAI"
    results = google_search(query, API_KEY, SEARCH_ENGINE_ID)
    with open("search_results.json", "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=4)
    
    # 处理搜索结果
    for item in results.get("items", []):
        # print("Title:", item["title"])
        # print("Snippet:", item["snippet"])
        # print("Link:", item["link"])
        # print("---" * 10)
        # 把Title, snippet, link写入字典
        # Title作为key,其他两个作为value
        key = item["title"]
        value = [item["snippet"], item["link"]]
        # 把字典写入列表
        # 用于后续的json文件写入
        list = {key: value}
        # print(list)
    
        # 以json格式输出搜索结果
        print(json.dumps(list, ensure_ascii=False, indent=4))
        print("---" * 10)
    
  • 输出结果 demo

    {
        "OpenAI": [
            "Introducing GPT-4, OpenAI's most advanced system.",
            "https://openai.com/"
        ]
    }
    ------------------------------
    {
        "OpenAI API": [
            "An API for accessing new AI models developed by OpenAI.",
            "https://platform.openai.com/account/api-keys"
        ]
    }
    ------------------------------
    {
        "Introducing ChatGPT": [
            "Nov 30, 2022 ... ... and learn about its strengths and weaknesses. During the research preview, usage of ChatGPT is free. Try it now at chat.openai.com.",
            "https://openai.com/blog/chatgpt"
        ]
    }
    ------------------------------
    
    

你可能感兴趣的:(python相关,python,开发语言)