javascript - Greasemonkey 脚本中的 XPath 未在 XHTML 页面上选择正确的节点

标签 javascript xpath xhtml 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 
);

只有 <a>侧边栏上的元素被选中,其余的仍然存在。请引用this, weibo.com, target page .

有没有办法选择所有属性为action-type="login"的元素? ?

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

最佳答案

问题是在将所有这些节点添加到页面之前脚本正在运行。它们稍后由页面的 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 和 the waitForKeyElements() utility 处理延迟内容问题。 :

    // ==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);
    

关于javascript - Greasemonkey 脚本中的 XPath 未在 XHTML 页面上选择正确的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13063386/

相关文章:

javascript - 未捕获( promise )DOMException : Failed to execute 'texImage2D' on 'WebGL2RenderingContext' : Tainted canvases may not be loaded

javascript - 在 Chrome 扩展程序中安全地存储 token /密码

php - 拒绝没有启用 javascript 的浏览器使用我的 php 站点

javascript - Express 和 Node JS : Accessing response parameters from Multipart form POST

java xpath 应该只显示没有属性的子节点,但显示所有

java - 如何通过Java使用Selenium点击元素

css - HTML 类中的管道字符

html - HTML 首字母缩略词 "span"代表什么?

javascript - 如何为 p :remoteCommand ajax call? 传递动态值

xml - 仅当信息存在时打印节点的值