【问题标题】:Is there a way to find all hidden elements that have text using selenium python有没有办法使用 selenium python 找到所有具有文本的隐藏元素
【发布时间】:2021-11-09 21:11:47
【问题描述】:

我正在尝试从多个网页中抓取所有已翻译的文本。 在开始抓取之前,页面必须完全翻译,为此我必须滚动页面。我在 Edge 中使用 selenium,它具有翻译功能。 这里的问题是它只翻译可见的文本,并且有些文本在按下某些按钮之前不会显示。

这是我的代码:

        options = EdgeOptions()
        options.add_experimental_option('excludeSwitches', ['enable-logging'])
        options.use_chromium = True
        options.add_extension('adblock.crx')
        capabilities = DesiredCapabilities.EDGE
        prefs = {
        "translate_whitelists": {input_lang:output_lang},
        "translate":{"enabled":"true"}}

        options.add_argument('--lang=en')
        options.add_experimental_option("prefs", prefs)

        driver = Edge(executable_path=PATH, options=options, desired_capabilities=capabilities)
        driver.maximize_window()

        driver.get(url)
       
        # This is to scroll through the page
        if input_lang != output_lang:
            total_height = int(driver.execute_script("return document.body.scrollHeight"))
            divisions = total_height // 20

            for i in range(1, total_height, divisions):
                driver.execute_script("window.scrollTo(0, {});".format(i))
                time.sleep(3)
            driver.execute_script(f"window.scrollTo(0, {total_height});")
            time.sleep(4)

有没有一种方法可以找到所有带有文本的隐藏元素并循环单击它们以使它们变得可见? 任何帮助将不胜感激

【问题讨论】:

    标签: javascript python html selenium beautifulsoup


    【解决方案1】:

    使用element.getAttribute("textContent") 而不是getText()

    getText() 使用innerText 并考虑元素显示属性,如果未显示,则不会检索任何内容

    虽然textContent 不关心元素是否显示,但它会按原样重试内容

    【讨论】:

    • 谢谢,但有没有办法让所有隐藏的文字都可见?因为我需要翻译它而边缘无法翻译不可见的内容
    • @Demaxl - browser.execute_script('arguments[0].style.display = "inherit";', element) 或其他显示选项,例如 block
    • @Mangohero1 谢谢它完全符合我的要求
    • 很高兴听到这个消息!
    猜你喜欢
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2015-04-10
    • 1970-01-01
    • 2022-10-23
    相关资源
    最近更新 更多