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

如何用Python实现谷歌自动搜索?解决Selenium报错及Excel输入需求

问题解决:Selenium谷歌自动搜索报错+读取Excel/CSV关键词

一、报错原因与修复

你遇到的AttributeError: 'str' object has no attribute 'capabilities'是因为Selenium 4.x版本API变更:webdriver.Chrome()不再直接接受驱动路径字符串作为参数,需通过Service类配置驱动,或借助Selenium Manager自动管理驱动(推荐,无需手动下载ChromeDriver)。

修复后的基础搜索代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# 初始化浏览器配置
options = Options()
# 可选:添加无头模式(后台运行)、防检测参数
# options.add_argument("--headless=new")
# options.add_argument("--disable-blink-features=AutomationControlled")

# 初始化浏览器(Selenium 4+自动匹配ChromeDriver)
browser = webdriver.Chrome(options=options)

# 单个关键词搜索示例
search_string = input("输入要搜索的内容:").replace(' ', '+')
browser.get(f"https://www.google.com/search?q={search_string}")

二、读取Excel/CSV关键词实现批量搜索

前置依赖安装

先安装数据处理库:

pip install pandas openpyxl

(openpyxl用于读取.xlsx格式Excel文件)

1. 读取CSV文件版本

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import pandas as pd
import time

# 浏览器配置
options = Options()
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

browser = webdriver.Chrome(options=options)
# 先访问谷歌首页,避免直接搜索被拦截
browser.get("https://www.google.com/")
time.sleep(2)

# 读取CSV,假设关键词列名为「关键词」
df = pd.read_csv("keywords.csv")
keywords = df["关键词"].dropna().tolist()  # 过滤空值

# 批量搜索
for keyword in keywords:
    search_str = keyword.strip().replace(' ', '+')
    browser.get(f"https://www.google.com/search?q={search_str}")
    time.sleep(3)  # 加等待时间,避免触发反爬

browser.quit()

2. 读取Excel文件版本

仅需替换读取文件的代码:

# 读取.xlsx格式Excel文件
df = pd.read_excel("keywords.xlsx", engine="openpyxl")

注意事项

  • Selenium 4.6+版本会自动匹配Chrome浏览器对应的驱动,无需手动下载ChromeDriver
  • 频繁自动搜索可能触发谷歌反爬,建议延长等待时间、添加随机间隔,或使用代理IP
  • 若需搜索多页结果,可修改URL的&start=参数:&start=10对应第二页,&start=20对应第三页,以此类推

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 03:38:16