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

Selenium无法获取指定类数据,如何正确定位该类元素?

解决ClinicalTrials.gov元素获取失败的问题

核心问题原因

你用By.CLASS_NAME传入多个类名(ct-layout_table tr-tableStyle tr-moreInfo)是错误的——By.CLASS_NAME仅支持单个类名匹配,多个类名组合需要用CSS选择器或XPATH来定位。

修正方案

  1. 替换定位方式:用By.CSS_SELECTOR,多类名的写法是用.连接所有类,即.ct-layout_table.tr-tableStyle.tr-moreInfo
  2. 优化代码逻辑:把浏览器驱动初始化移到循环外,避免重复创建销毁;用显式等待替代固定time.sleep,提升稳定性和效率

修改后的代码

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

liste = []
linkss = ['https://ClinicalTrials.gov/show/NCT05768724','https://ClinicalTrials.gov/show/NCT05768607']

# 初始化浏览器驱动,放在循环外
path = r"C:\Users\kaant\Downloads\chromedriver.exe"
service = Service(executable_path=path)
options = uc.ChromeOptions() 
options.headless = True 
driver = uc.Chrome(options=options, service=service)

try:
    for data in linkss:
        driver.get(data)  
        # 显式等待目标元素加载完成,最长等待10秒
        infos = WebDriverWait(driver, 10).until(
            EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".ct-layout_table.tr-tableStyle.tr-moreInfo"))
        )
        c = [info.text for info in infos]
        liste.append(c)
finally:
    driver.quit()

额外说明

  • 显式等待会在元素出现后立即执行,比固定睡眠更高效,也能避免因网络延迟导致的元素未加载问题
  • 如果返回的文本格式仍有问题,可以尝试获取元素的innerHTML或拆分单元格内容(比如定位每个<td>元素提取文本),进一步整理数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 09:35:15