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

Python Selenium如何查找带文本的隐藏元素实现全量网页翻译内容抓取

解决方案

你可以通过Selenium执行JS来筛选所有包含文本且处于隐藏状态、绑定了点击展开逻辑的元素,再循环点击触发展开。具体实现思路和代码如下:

第一步:明确需要点击的展开元素特征

通常隐藏了文本内容的可点击展开元素会有以下特征,可以作为筛选条件:

  • 元素有hidden属性,或CSS属性display: none、visibility: hidden
  • 带有aria-expanded="false"属性(无障碍规范下的折叠元素标记)
  • 类名/文本包含展开、更多、查看全部、more、expand、collapse等关键词
  • 子元素包含非空文本内容

第二步:代码实现

你可以在现有滚动加载完成的代码后添加如下逻辑:

import time
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.common.exceptions import ElementClickInterceptedException, ElementNotInteractableException

# 滚动完成后执行展开逻辑
if input_lang != output_lang:
    # 执行JS获取所有可点击的隐藏文本父元素
    expandable_elements = driver.execute_script("""
        const targets = [];
        // 遍历所有元素筛选符合条件的
        document.querySelectorAll('*').forEach(el => {
            // 跳过无点击事件、无文本内容的元素
            if (!el.onclick && el.getAttribute('onclick') === null && getComputedStyle(el).cursor !== 'pointer') return;
            const text = el.textContent.trim();
            if (!text || text.length < 2) return;
            // 筛选隐藏/折叠状态的元素
            const style = getComputedStyle(el);
            const isHidden = el.hidden || style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0';
            const isCollapsed = el.getAttribute('aria-expanded') === 'false';
            // 筛选类名/文本含展开关键词的元素
            const hasExpandKeyword = /(展开|更多|查看全部|more|expand|collapse|show all)/i.test(el.className + ' ' + text);
            if ((isHidden || isCollapsed || hasExpandKeyword) && el.offsetParent !== null) {
                targets.push(el);
            }
        });
        // 去重,避免重复点击同一个元素
        return [...new Set(targets)];
    """)

    # 循环点击展开
    wait = WebDriverWait(driver, 5)
    for elem in expandable_elements:
        try:
            # 滚动到元素可见位置再点击
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", elem)
            time.sleep(0.5)
            # 等待元素可点击
            wait.until(EC.element_to_be_clickable(elem))
            elem.click()
            # 等待翻译触发完成
            time.sleep(2)
        except (ElementClickInterceptedException, ElementNotInteractableException):
            # 跳过被遮挡、不可交互的元素
            continue
        except Exception:
            continue

    # 全部展开后再全局滚动一遍,触发所有内容翻译
    total_height = int(driver.execute_script("return document.body.scrollHeight"))
    driver.execute_script(f"window.scrollTo(0, {total_height});")
    time.sleep(3)

注意事项

  • 如果目标网站的展开按钮有统一的选择器,可以直接用driver.find_elements()筛选,比全量遍历元素效率高很多
  • 可以根据你抓取的站点特征调整JS里的正则匹配关键词,减少误判
  • 部分站点展开后会加载新的内容,你可以在点击完成后重新执行一遍筛选展开的逻辑,确保多层折叠的内容也被展开

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:45:03