在Greasemonkey脚本中,XPath没有在XHTML页面上选择正确的节点 [英] XPath, in a Greasemonkey script, is not selecting right nodes on an XHTML page

查看:83
本文介绍了在Greasemonkey脚本中,XPath没有在XHTML页面上选择正确的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 weibo.com 开发Greasemonkey脚本.我无法使用XHTML页面上的XPath来选择元素.

I'm working on a Greasemonkey script for weibo.com. I can't pick the elements using XPath on the XHTML page.

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

This code fails to grab the elements I want:

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目标页面.

Only the <a> elements on the sidebar are picked and the rest are still there. Please refer to this, weibo.com, target page. 

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

Is there anyway to pick all the elements with attribute action-type="login"?

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

I used "//x:a[@action-type='login']", but It didn't work.

推荐答案

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

The problem is that the script is running before all of these nodes are added to the page. They are added by the page's AJAX later.

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

So, you could add a time-delay to your script. But:

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

  1. If you just want to grab select elements, you almost never need to use XPath. Use querySelectorAll() or jQuery instead. Here's a basic example with querySelectorAll and no time delay:

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


这是一个完整的Greasemonkey脚本,该脚本使用jQuery和 waitForKeyElements()实用程序:

Here's a complete Greasemonkey script, that handles the delayed content problem using jQuery and 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);

这篇关于在Greasemonkey脚本中,XPath没有在XHTML页面上选择正确的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆