我正在为 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>
侧边栏上的元素被选取,其余的仍然存在。请参阅.
无论如何,有没有选择所有具有属性的元素action-type="login"
?
I used "//x:a[@action-type='login']"
,但没有成功。
问题在于脚本在所有这些节点添加到页面之前就已运行。它们稍后由页面的 AJAX 添加。
因此,您可以在脚本中添加时间延迟。But:
-
如果您只想获取选定的元素,则几乎不需要使用 XPath。使用querySelectorAll() https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll或 jQuery 代替。这是一个基本示例querySelectorAll
并且没有时间延迟:
var allLinks = document.querySelectorAll ("a[action-type='login']");
if (allLinks.length) {
// PROCESS NODES AS DESIRED, HERE.
}
-
这是一个完整的 Greasemonkey 脚本,使用 jQuery 处理延迟内容问题,并且waitForKeyElements() 实用程序 https://gist.github.com/2625891:
// ==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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)