在Greasemonkey脚本中,XPath没有在XHTML页面上选择正确的节点

Den*_*how 3 javascript xhtml xpath greasemonkey weibo

我正在为weibo.com制作 Greasemonkey脚本.我无法在XHTML页面上使用XPath选择元素.

此代码无法获取我想要的元素:

function resolver(prefix) {
    return prefix === 'x' ? 'http://www.w3.org/1999/xhtml' : null;
}
var allLinks, thisLink;
allLinks = document.evaluate(
  "//x:a[@href]", 
  document, 
  resolver, 
  XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, 
  null 
);
Run Code Online (Sandbox Code Playgroud)

<a>选择侧栏上的元素,其余元素仍在那里.请参考这个weibo.com目标页面.

无论如何选择具有属性的所有元素action-type="login"

我用过"//x:a[@action-type='login']",但没用.

Bro*_*ams 5

问题是在将所有这些节点添加到页面之前脚本正在运行.它们稍后由页面的AJAX添加.

因此,您可以为脚本添加延时.但:

  1. 如果你只想抓取选择元素,你几乎不需要使用XPath.请改用querySelectorAll() 或使用jQuery.这是一个基本的例子,querySelectorAll没有时间延迟:

    var allLinks = document.querySelectorAll ("a[action-type='login']");
    if (allLinks.length) {
        // PROCESS NODES AS DESIRED, HERE.
    }
    
    Run Code Online (Sandbox Code Playgroud)


  2. 这是一个完整的Greasemonkey脚本,它使用jQuery和waitForKeyElements()实用程序处理延迟的内容问题:

    // ==UserScript==
    // @name        _Weibo, hilite login links
    // @include     http://s.weibo.com/weibo/*
    // @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
    // @require     https://gist.github.com/raw/2625891/waitForKeyElements.js
    // @grant    GM_addStyle
    // ==/UserScript==
    /*- The @grant directive is needed to work around a design change
        introduced in GM 1.0.   It restores the sandbox.
    */
    
    function processLoginLinks (jNode) {
        //***** YOUR CODE HERE *****
        jNode.css ("background", "lime");
    }
    
    waitForKeyElements ("a[action-type='login']", processLoginLinks);
    
    Run Code Online (Sandbox Code Playgroud)