You need to enable JavaScript to run this app. 基于Python Selenium实现Google Earth网页版坐标拾取的元素定位问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

基于Python Selenium实现Google Earth网页版坐标拾取的元素定位问题咨询

Google Earth网页版爬虫坐标定位问题修正

定位失效的核心原因

  • Google Earth Web的界面组件基于Shadow DOM封装实现,坐标展示节点不在页面公开的常规DOM树中,常规的ID、CSS选择器、XPath检索不会自动穿透Shadow根节点,因此无论使用哪种常规定位方式都无法匹配到目标元素
  • 代码中使用的find_elements_by_id属于Selenium3时代的旧版API,在Selenium4.x版本中已被正式弃用,必须替换为基于By枚举的新版定位接口
  • 右下角的坐标元素是鼠标悬停在WebGL画布时才会动态渲染的节点,并非页面加载完成就常驻显示,未做等待逻辑时很容易出现节点不存在的情况

可运行的修正实现代码

import mouse
import keyboard
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-logging"])
# 规避Google Earth的自动化测试检测
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(options=options)
driver.get('https://earth.google.com/web')
# 预留页面初始化加载时间
time.sleep(8)

def traverse_shadow_dom(selectors_chain):
    """递归穿透多层Shadow DOM定位目标元素"""
    current_node = driver.find_element(By.CSS_SELECTOR, selectors_chain[0])
    for selector in selectors_chain[1:]:
        current_node = current_node.shadow_root.find_element(By.CSS_SELECTOR, selector)
    return current_node

while True:
    if mouse.is_pressed(button='left') and keyboard.is_pressed('shift'):
        try:
            # 按DOM层级穿透定位坐标展示节点
            coord_text = traverse_shadow_dom(
                [
                    'earth-scene-viewer',
                    '.coordinates'
                ]
            ).text
            print(f"捕获坐标: {coord_text}")
        except NoSuchElementException:
            print('No coordinates found!')
        time.sleep(0.2)

运行注意事项

  • 首次打开页面时需要手动完成服务条款同意、地球视角初始加载的交互步骤,脚本不会自动处理这类前置流程
  • 坐标元素仅当光标在WebGL画布区域内时才会渲染,按住Shift点击时光标如果不在画布范围内,会触发元素找不到的提示
  • mouse、keyboard库的按键检测依赖系统权限,macOS环境下需要给运行脚本的终端授予辅助功能权限,否则无法正常捕获按键状态
  • 如果Google Earth版本更新导致选择器不匹配,可以打开浏览器开发者工具,手动选中坐标展示元素,逐层记录其所在的Shadow DOM节点层级,调整选择器链即可正常定位

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 11:24:05