我正在为 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 添加。
因此,您可以在脚本中添加时间延迟。 但是:
如果您只想抓取选择的元素,您几乎不需要使用 XPath。使用
querySelectorAll()
或 jQuery 代替。这是一个使用querySelectorAll
且没有时间延迟的基本示例:var allLinks = document.querySelectorAll ("a[action-type='login']"); if (allLinks.length) { // PROCESS NODES AS DESIRED, HERE. }
这是一个完整的 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/