3

我正在为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 
);

只有<a>侧边栏上的元素被选中,其余的仍然存在。请参考这个,weibo.com,目标页面。 

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

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

4

1 回答 1

5

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

因此,您可以在脚本中添加时间延迟。但:

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

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


  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);
    
于 2012-10-25T08:15:08.887 回答