代码之家  ›  专栏  ›  技术社区  ›  darius

附录如何使用用户脚本按类名从(动态)div中提取文本?

  •  2
  • darius  · 技术社区  · 7 年前

    如何使用JavaScript从以下对象提取值2083236893?

    <div class="gwt-Label">2083236893</div>
    

    我为Firefox 52.2.1(32位)安装了Greasemonkey 3.17,并测试了提供的每个代码示例,但都失败了。

    var html = document.getElementsByClassName("gwt-Label")[0];
    alert(html.innerHTML);
    

    上述示例来自: Accessing Div, by class name, with javascript .

    代码应该在网页完全下载时运行吗?

    附加内容:

    var elements = document.getElementsByClassName("gwt-Label")[0];
    alert(elements.innerHTML);
    

    如果

    elements.length = 0
    

    可能是文档未完全加载或查询结果为0-没有DIV对象包含查询字符串中的类名

    Firebug可以为文档(浏览器中的HTML版本)中的选定对象(innerHTML或innerTEXT)生成XPath,以验证查询中的类名是否正确且存在。

    设置更大的超时值可以让HTML文档完全加载,从而使脚本通过Greasemonkey或类似的附加组件运行,通过

    console.log(HTMLCollection.length) 
    

    见上文。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Brock Adams    7 年前

    class="gwt-Label" 在HTML中,强烈暗示页面由 Google Web Toolkit --这意味着页面是AJAX驱动的,静态技术,就像其他一些答案一样,将无法工作。

    使用AJAX感知技术,如 waitForKeyElements() . 这里有一个 完整的脚本 将打印 gwt-Label 浏览器控制台的值。( Ctrl键 转移 打开所述控制台。):

    // ==UserScript==
    // @name     _Print gwt-Label text
    // @match    *://YOUR_SERVER.COM/YOUR_PATH/*
    // @match    https://stacksnippets.net/js*
    // @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
    // @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
    // @grant    GM_addStyle
    // ==/UserScript==
    //- The @grant directive is needed to restore the proper sandbox.
    
    waitForKeyElements (".gwt-Label", printNodeText);
    
    function printNodeText (jNode) {
        console.log ("gwt-Label value: ", jNode.text ().trim () );
    }
    

    如果有多个标签,这将打印每个标签。

    注意,waitForKeyElements使用jQuery选择器。



    can测试 通过使用Greasemonkey、Tampermonkey、Violentmonkey或类似工具安装上述脚本,然后运行以下代码段:

    var lblbNum = 0;
    function addLableLine () {
        lblbNum++;
        $("body").append(`<div class="gwt-Label">New label: ${lblbNum}</div>`);
    }
    setInterval (addLableLine, 1333);  // New line every 1.3 seconds.
    .gwt-Label {display: inline-block;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="gwt-Label">2083236893</div>

    然后您将看到:

    gwt-Label value:  2083236893
    gwt-Label value:  New label: 1
    gwt-Label value:  New label: 2
    etc...
    

    在浏览器控制台中。

        2
  •  1
  •   Peter Mortensen code4jhon    7 年前

    如果您希望使用。jQuery中的text(),这可能更简单!

    查看此链接: http://api.jquery.com/text/

    这将选择您的文本:

    $(window).load(function(){
        $(".gwt-Label").text();
    });