You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python3 AI程序添加谷歌搜索功能:打开Chrome并读取结果

Hey there! Let's tackle your two Python questions one by one—both are practical use cases, so I’ll walk you through actionable solutions.

1. 编写Python3程序实现谷歌搜索

You’ve got two solid options here, depending on whether you need a quick prototype or a production-grade stable solution:

选项A:用第三方库快速实现(适合原型)

The googlesearch-python library wraps Google’s search results nicely without needing API keys. Here’s how to use it:

  • First, install the package:
    pip install googlesearch-python
    
  • Then write your search code:
    from googlesearch import search
    
    def google_search(query, num_results=5):
        # 获取搜索结果的链接和标题
        results = []
        for result in search(query, num_results=num_results, lang="en"):
            results.append(result)
        return results
    
    # 示例调用
    query = "Python AI best practices"
    search_results = google_search(query)
    for idx, res in enumerate(search_results, 1):
        print(f"{idx}. {res}")
    

This will spit out the top search result URLs for your query. Note that this relies on web scraping, so it might break if Google changes its page structure—great for testing, but not ideal for long-term production.

选项B:使用谷歌自定义搜索API(适合生产环境)

For a more reliable solution, use Google’s Custom Search JSON API. You’ll need two things first:

  1. A Google Cloud API key (create one in the Google Cloud Console)
  2. A Custom Search Engine ID (set this up via the Custom Search Engine page)

Once you have those, use the requests library to make API calls:

  • Install requests if you haven’t:
    pip install requests
    
  • Example code:
    import requests
    
    def google_search_api(query, api_key, cx_id, num_results=5):
        url = "https://www.googleapis.com/customsearch/v1"
        params = {
            "q": query,
            "key": api_key,
            "cx": cx_id,
            "num": num_results
        }
        response = requests.get(url, params=params)
        results = response.json()
        
        # 提取结果标题和链接
        search_results = []
        if "items" in results:
            for item in results["items"]:
                search_results.append(f"{item['title']} - {item['link']}")
        return search_results
    
    # 示例调用(替换成你的API密钥和搜索引擎ID)
    query = "Python AI best practices"
    api_key = "YOUR_GOOGLE_API_KEY"
    cx_id = "YOUR_CUSTOM_SEARCH_ENGINE_ID"
    results = google_search_api(query, api_key, cx_id)
    for res in results:
        print(res)
    

This method is rate-limited but far more stable than scraping.

2. 在AI程序中集成Chrome搜索并读取前两行结果

To launch Chrome, run a search, and extract results, you’ll need the selenium library to automate the browser. Here’s a step-by-step guide:

第一步:安装依赖

  • Install selenium:
    pip install selenium
    
  • Download ChromeDriver: Make sure the version matches your installed Chrome browser. You can get it from the official ChromeDriver site, then either add it to your system PATH or specify its path in the code.

第二步:编写集成代码

This script will listen for the "search google ..." command, extract the query, launch Chrome, and pull the first two result snippets:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

def handle_google_search(command):
    # 提取搜索关键词(去掉"search google "前缀)
    query = command.replace("search google ", "").strip()
    if not query:
        print("Please provide a search term after 'search google'.")
        return
    
    # 初始化Chrome浏览器
    # 如果ChromeDriver不在PATH里,指定executable_path参数:
    # driver = webdriver.Chrome(executable_path="/path/to/chromedriver")
    driver = webdriver.Chrome()
    
    try:
        # 打开谷歌搜索页面
        driver.get("https://www.google.com")
        
        # 等待搜索框加载并输入关键词
        search_box = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.NAME, "q"))
        )
        search_box.send_keys(query)
        search_box.send_keys(Keys.RETURN)
        
        # 等待搜索结果加载
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "div.g"))
        )
        
        # 获取前两行结果的文本内容
        results = driver.find_elements(By.CSS_SELECTOR, "div.g")[:2]
        if results:
            print("Top 2 search results:")
            for idx, result in enumerate(results, 1):
                # 提取标题和摘要
                title = result.find_element(By.TAG_NAME, "h3").text
                snippet = result.find_element(By.CSS_SELECTOR, "div.IsZvec").text
                print(f"\n{idx}. {title}")
                print(f"   {snippet}")
        else:
            print("No search results found.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")
    finally:
        # 关闭浏览器(可选:如果想保持浏览器打开,注释掉这行)
        time.sleep(5)  # 留5秒查看页面,然后关闭
        driver.quit()

# 示例:模拟用户输入指令
user_input = "search google Python AI libraries for beginners"
if user_input.startswith("search google "):
    handle_google_search(user_input)

关键说明

  • We use WebDriverWait to ensure elements load before interacting with them—this prevents race conditions.
  • The CSS selectors (div.g, div.IsZvec) target Google’s search result containers and snippets. Note that Google might change these selectors over time, so you may need to adjust them if the script breaks.
  • If you want the browser to stay open after the script runs, comment out the driver.quit() line.

内容的提问来源于stack exchange,提问作者Prashasth Nair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:35:43