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

Selenium筛选MarineTraffic指定搜索结果问题求助

问题与解决方法

问题背景

在marinetraffic.com的搜索结果里:

  • 第1条结果不符合要求,第2、4条符合
  • 符合条件的结果分别在class为jss90和jss89的div标签内
  • 用browser.find_elements(By.XPATH, "//div[contains(@class, 'jss90')]")无法获取目标元素
  • 需要筛选出jss90标签含ATLANTICA且jss89标签含Bulk Carrier的结果,收集到列表后点击第一个匹配项

解决步骤

1. 定位失败原因分析

jss90这类class是React框架动态生成的,会随页面版本或加载状态变化,直接依赖它定位很不稳定。应该结合文本内容和元素层级关系来写XPath,避开动态class的坑。

2. 编写精准的组合条件XPath

要同时匹配两个文本条件,我们可以通过元素的层级关联来定位整个结果项(假设两个div属于同一个父节点):

# 定位同时满足双条件的完整结果项
matching_items = browser.find_elements(
    By.XPATH,
    "//div[contains(@class, 'jss90') and contains(text(), 'ATLANTICA')]/../div[contains(@class, 'jss89') and contains(text(), 'Bulk Carrier')]/.."
)

如果jss90是jss89的前序兄弟节点,也可以这么写:

matching_items = browser.find_elements(
    By.XPATH,
    "//div[contains(@class, 'jss89') and contains(text(), 'Bulk Carrier')]/preceding-sibling::div[contains(@class, 'jss90') and contains(text(), 'ATLANTICA')]/.."
)

3. 处理匹配列表并点击第一个结果

if matching_items:
    # 点击第一个符合条件的结果
    matching_items[0].click()
else:
    print("没有找到符合要求的搜索结果")

4. 动态加载场景的适配

如果搜索结果是异步加载的,必须先等待元素出现再操作:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 最多等待10秒,直到匹配元素加载完成
wait = WebDriverWait(browser, 10)
matching_items = wait.until(
    EC.presence_of_all_elements_located(
        (By.XPATH, "//div[contains(@class, 'jss89') and contains(text(), 'Bulk Carrier')]/preceding-sibling::div[contains(@class, 'jss90') and contains(text(), 'ATLANTICA')]/..")
    )
)

if matching_items:
    matching_items[0].click()

额外建议

尽量避免依赖动态生成的class(比如jssxx这类),可以查看元素是否有其他固定属性(如data-*属性),或者直接用文本内容定位,这样代码更稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:15:26