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

Selenium定位Google Place ID搜索框失败,求排查解决方案

解决Google Place ID搜索框定位失败的问题

问题原因

该页面的搜索框嵌套在iframe中,直接在主页面DOM上下文查找元素会失败,并非反爬限制导致。

解决方案

先切换到包含搜索框的iframe上下文,再进行元素定位,具体步骤和代码如下:

修正后的测试代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
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
from webdriver_manager.chrome import ChromeDriverManager

place_id_url = "https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder#maps_places_placeid_finder-typescript"

options = Options()
options.add_experimental_option("detach", True)

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
driver.get(place_id_url)

# 等待iframe加载完成并切换到该iframe
iframe = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, "iframe.devsite-iframe"))
)
driver.switch_to.frame(iframe)

# 现在可以正常定位搜索框
searchbox = WebDriverWait(driver, 5).until(
    EC.element_to_be_clickable((By.ID, "pac-input"))
)
searchbox.clear()
keyword = "Dunham Park"
searchbox.send_keys(keyword)

关键说明

  • 页面中的地图示例区域被封装在class为devsite-iframe的iframe里,必须先切换到该iframe才能访问内部元素
  • 切换iframe后,使用By.ID, "pac-input"这种最稳定的定位方式即可成功找到搜索框
  • 若后续需要操作主页面元素,记得用driver.switch_to.default_content()切回主上下文

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:17:16