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

使用Python Selenium定位Google Images按钮报错的技术问题

解决Selenium操作Google主页的两个问题

问题1:executable_path弃用警告

原代码中直接通过webdriver.Chrome(r"D:\driver\chromedriver.exe")初始化驱动的方式已被弃用,需要改用Service类来指定驱动路径。

修正步骤:

  • 从selenium.webdriver.chrome.service导入Service类
  • 实例化Service对象并传入驱动路径,再将其作为参数传给webdriver.Chrome()

问题2:NoSuchElementException(找不到元素)

Google主页的"Images"按钮并没有name="Images"这个属性,直接用By.NAME定位会失败。正确的定位方式可以选择:

  • 链接文本定位(By.LINK_TEXT):针对英文页面的"Images"或中文页面的"图片"
  • XPath定位:通过元素的文本或其他属性组合定位

另外,time.sleep(5)是固定等待,可靠性差,建议用显式等待(WebDriverWait)等待元素可点击,避免因页面加载延迟导致的定位失败。

修正后的完整代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 初始化驱动,解决弃用警告
service = Service(r"D:\driver\chromedriver.exe")
driver = webdriver.Chrome(service=service)

driver.get("https://www.google.com/")
driver.maximize_window()

# 显式等待元素可点击,最多等待10秒
# 若为中文页面,将"Images"改为"图片"
images_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.LINK_TEXT, "Images"))
)
images_button.click()

# 操作完成后可关闭驱动
# driver.quit()

补充说明

  • 确保ChromeDriver版本与Chrome浏览器版本一致,否则可能出现兼容性问题
  • 如果Google主页自动跳转到本地化页面(比如中文),需将定位文本改为对应语言的"图片"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:45:29