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

Python Selenium定位MarineTraffic搜索框XPATH失败 无法定位元素问题求解

定位失败原因排查&解决方案

核心问题

  1. 网站首次访问会弹出Cookie合规弹窗,未处理弹窗会阻断后续元素交互,同时动态渲染的搜索组件挂载慢于固定5秒的等待时间,导致查找元素时DOM中还未生成目标节点
  2. 搜索框位于顶层DOM,不存在iframe嵌套,无需切换iframe操作
  3. 之前的By.ID定位写法错误,By.ID对应的参数仅需传入ID字符串,不需要填写XPath路径,(By.ID, '//*[@id="searchMT"]')是无效写法
  4. 原代码使用http协议访问,会触发网站301重定向到https地址,额外增加页面加载耗时,进一步降低固定sleep的可靠性

可运行修正代码

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

Path = "C:\Selenium\chromedriver.exe"
S = Service(Path)
driver = webdriver.Chrome(service = S)
# 超时时间可根据自身网络情况调整
wait = WebDriverWait(driver, 10)

# 直接使用https地址避免重定向
driver.get("https://www.marinetraffic.com")
driver.maximize_window()

# 先处理Cookie同意弹窗
agree_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(),'AGREE')]")))
agree_btn.click()

# 等待搜索框加载完成后输入内容
search_input = wait.until(EC.element_to_be_clickable((By.ID, "searchMT")))
search_input.send_keys("vessel", Keys.ENTER)

额外注意事项

  • 请确保ChromeDriver的大版本和本地安装的Chrome浏览器大版本一致,版本差异过大会导致未知交互异常
  • 该网站存在反爬机制,频繁发起请求可能会触发验证码校验或IP封禁,建议操作之间添加合理的等待间隔
  • 如果网络环境访问该网站速度较慢,可适当调大WebDriverWait的超时参数,避免还没加载完成就超时报错

内容的提问来源于stack exchange,提问作者Daniel Guimarães

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:06:04