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

如何用Python+Selenium结合CSS选择器获取announcementTitle内容?

使用Python + Selenium结合CSS选择器获取公告标题内容

给定HTML代码

</template>
</el-table-column>
<el-table-column prop="announcementTitle" label="公告标题">
    <template slot-scope="scope">
    <span class="ahover">
        <a v-html="scope.row.announcementTitle" target="_blank" :href="linkLastPage(scope.row)"></a>
        <span v-show="checkDocType(scope.row.adjunctType)" class="icon-f"><i class="iconfont" :class="[checkDocType(scope.row.adjunctType)]"></i></span>
    </span>
    </template>

问题

现需使用Python + Selenium结合CSS选择器获取announcementTitle的内容,代码应如何编写?


解决方案

由于页面是Vue动态渲染的,必须先确保目标元素加载完成,再通过CSS选择器定位获取内容。

核心思路

  1. 用WebDriverWait等待元素渲染完成,避免因页面加载延迟导致定位失败
  2. 选择合适的CSS选择器定位承载标题的<a>元素,优先使用精准选择器避免冲突
  3. 根据渲染方式选择text或innerHTML获取内容

完整代码示例

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 初始化Chrome驱动(需确保ChromeDriver已配置好环境变量)
driver = webdriver.Chrome()
driver.get("你的目标页面URL")

try:
    # 等待目标元素加载,超时时间10秒
    # 推荐使用精准选择器:匹配指定prop属性的表格列下的a标签
    title_element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, 'el-table-column[prop="announcementTitle"] .ahover a'))
    )

    # 获取标题内容:若text方法为空,改用innerHTML获取v-html渲染的内容
    announcement_title = title_element.text or title_element.get_attribute("innerHTML")
    print(f"公告标题:{announcement_title}")

    # 如果需要获取所有公告标题(表格多行),改用find_elements遍历
    # title_elements = WebDriverWait(driver, 10).until(
    #     EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'el-table-column[prop="announcementTitle"] .ahover a'))
    # )
    # for idx, elem in enumerate(title_elements, 1):
    #     title = elem.text or elem.get_attribute("innerHTML")
    #     print(f"第{idx}条公告标题:{title}")

finally:
    driver.quit()

可选CSS选择器方案

  • 简化版选择器(页面无同类元素冲突时可用):.ahover > a
  • 基于标签层级的选择器:span.ahover a

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:17:11