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

Selenium定位谷歌搜索框报错:name 'By' is not defined 求解

解决Selenium定位谷歌搜索框时的"By未定义"问题

错误原因

你使用了By.CLASS_NAME但未导入Selenium的By类,Python无法识别该对象,因此抛出name 'By' is not defined错误。

修正方案

  1. 补充导入By类的语句
  2. 谷歌搜索框的name属性为q,相比class namegLFyf更稳定,推荐使用该属性定位
  3. 新增显式等待逻辑,避免页面未加载完成导致元素找不到的问题

修正后的完整代码

!pip install selenium
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
# 新增导入By类的语句
from selenium.webdriver.common.by import By
# 新增显式等待相关模块
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("http://www.google.com")

# 等待搜索框加载完成,最多等待10秒
search = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.NAME, "q"))
)
search.send_keys("test")
search.send_keys(Keys.RETURN)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:52:04