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

使用Selenium ChromeDriver在谷歌搜索无法输入,求正确代码方案

解决谷歌搜索框无法输入的问题

问题原因

你之前使用的class属性desktopOldAutosuggestTheme-UyU36RyhCTcuRs_sXL9b是动态生成的,谷歌页面元素的class会频繁更新,导致定位失效。

正确的定位方式

推荐使用更稳定的属性定位谷歌搜索框:

方式1:通过name属性定位

谷歌搜索框的name属性为q,这个属性长期稳定,不会轻易变化:

driver.findElement(By.name("q")).sendKeys("HBCV00000ODHHV");

方式2:通过id属性定位

搜索框的id通常是APjFqb(当前页面该id存在时可用):

driver.findElement(By.id("APjFqb")).sendKeys("HBCV00000ODHHV");

方式3:通用xpath定位

如果上述方式失效,可通过placeholder属性定位,搜索框的placeholder一般为“搜索 Google 或输入网址”:

driver.findElement(By.xpath("//input[@placeholder='搜索 Google 或输入网址']")).sendKeys("HBCV00000ODHHV");

额外建议

确保定位元素前页面已完全加载,可添加显式等待避免元素找不到的问题:

WebElement searchBox = new WebDriverWait(driver, 10)
        .until(ExpectedConditions.presenceOfElementLocated(By.name("q")));
searchBox.sendKeys("HBCV00000ODHHV");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:55:23