`
tory320
  • 浏览: 33174 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

document.evaluate

阅读更多

使用 Greasemonkey 时会遇到的功能最为强大的一个工具就是 evaluate 函数。通过使用XPath这种查询语言,它可以用来寻找页面中的元素,属性和文本。

举个例子来说,如果您想获得某个页面上的全部链接。您也许会想到使用document.getElementsByTagName('a');但是如果您还要继续检查是否每个链接都具有href属性,因为<a>还可以用来作为锚名称使用,这时,您需要使用Firefox内建的 XPath 支持去获取全部具有href属性的<a>元素。

例子: 获取页面上的全部链接

var allLinks, thisLink;
allLinks = document.evaluate(
     '//a[@href]',
     document,
     null,
     XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
     null);
for (var i = 0; i < allLinks.snapshotLength; i++) {
     thisLink = allLinks.snapshotItem(i);
     // do something with thisLink
}

这里,document.evaluate 是关键的部分。 它把 XPath 查询语句作为一个字符串,其它的参数稍后再做解释。 这条 XPath   查询语句可以找到全部具有href属性的<a>元素,并将它们按照随机的顺序依次返回。(这就是说,第一个被返回的元素并一定也是页面上的第一个这样的元素。) 随后,您就可以用 allLinks.snapshotItem(i) 函数访问每一个元素。


XPath表达式所能做到的甚至会使您惊讶。请看下面这个例子,它获取了全部具有title属性的元素。




例子: 获取全部具有title属性的元素

var allElements, thisElement;
allElements = document.evaluate(
     '//*[@title]',
     document,
     null,
     XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
     null);
for (var i = 0; i < allElements.snapshotLength; i++) {
     thisElement = allElements.snapshotItem(i);
     switch (thisElement.nodeName.toUpperCase()) {
         case 'A':
             // this is a link, do something
             break;
         case 'IMG':
             // this is an image, do something else
             break;
         default:
             // do something with other kinds of HTML elements
     }
}




如果您已经引用了某个元素(例如上面的 thisElement),您就可以用 thisElement.nodeName 来替代它所对应的在   HTML 页面中的标签名称。如果被访问的这个页面是以 text/html 的方式被服务器执行, 那么标签名称总是用大写子母返回,不论它在原始页面是如何定义的。 如果页面是 application/xhtml+xml 方式的, 那么标签名称就会以小写子母返回。 不论哪种情况,我总是用   thisElement.nodeName.toUpperCase() 得到大写的标签名称。 


这是另外一个 XPath 查询,它返回了 div 中的一个特殊的类。


例子: 获取 div 中的 sponsoredlink 类

var allDivs, thisDiv;
allDivs = document.evaluate(
     "//div[@class='sponsoredlink']",
     document,
     null,
     XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
     null);
for (var i = 0; i < allDivs.snapshotLength; i++) {
     thisDiv = allDivs.snapshotItem(i);
     // do something with thisDiv
}

注意我在 XPath 查询语句外使用了双引号,这样在语句内部就可以使用单引号。


在 document.evaluate 函数中有很多参数。第二个参数 (在前两个例子中都是docoment) 可以是一个元素, XPath 查询只返回包含在这个元素内的元素。所以,如果您已经引用了一个元素(比如, 通过 document.getElementById 或者 通过   document.getElementsByTagName 得到的数组中的一个元素), 那么您就可以限制查询只返回这个元素的子元素。


第三个参数是对一个叫做 namespace resolver 函数的引用, 它只有在工作在 application/xhtml+xml 类型的页面上的用户脚本中是有效的。即使您对它不是很了解也没有关系,因为那种类型的页面不是很多,您可能一次也遇不到。如果您很想知道它是如何使用的,请参考   Mozilla XPath documentation (http://www-jcsu.jesus.cam.ac.uk/~jg307/mozilla/xpath-tutorial.html),那里解释了它的用法。


第四个参数是结果的返回方式。在前面的两个例子中都使用了 XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, 它将结果以随机的方式返回。我使用的几乎全部都是这种方式,但是,出于某种原因,您想让结果以它们在页面上出现的顺序返回,您可以使用   XPathResult.ORDERED_NODE_SNAPSHOT_TYPE 这种方式。 Mozilla XPath documentation (http://www-jcsu.jesus.cam.ac.uk/~jg307/mozilla/xpath-tutorial.html)还给出了另外的一些用例。


第五个参数用来合并两次 XPath 查询的结果。 在获得第一次调用 document.evaluate 得到的结果之后,它将两次查询的结果一起返回。在前面的两个例子中,这个参数都用了null,这意味着我们只想获得本次查询的结果。


现在您明白了吗?XPath 既可以很简单,也可以很难,这取决于您要如何使用它。在此我强烈推荐您尽快去阅读 http://www.w3school.com.cn/xpath/xpath_syntax.asp,从而了解更多的 XPath 语法。至于 document.evaluate 函数的其它参数, 我几乎从来不使用它们。事实上,您可以自己定义一个函数来封装它们。


例子: 自定义的 xpath 函数

function xpath(query) {
     return document.evaluate(query, document, null,
         XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
}


在定义了这个函数之后,您就可以调用 xpath('//a[@href]') 来获得某个页面上的全部链接, 或者调用 xpath('//* [@title]') 来获得具有 title 属性的元素。您仍然需要通过 snapshotItem 函数来访问结果中的每一项,这个函数的类型并不是一个规则的Javascript数组。
分享到:
评论

相关推荐

    Prototype Selector对象学习

    FF是document.evaluate;Opera和Safari是selectorsAPI。第二部分是对外提供的基本函数,像findElements,match等,Element对象里面的很多方法就是直接调用这个对象里面的方法。第三部分就是XPath等一些查询DOM的匹配...

    JS实现问卷星自动填问卷脚本并在两秒自动提交功能

    脚本只使用问卷星,多选题目前为选中任意选项数量!!!!!!! 最近看到很多群里都在发问卷连接,各种求帮忙,正好这两天没任务,尝试写了自动填问卷的脚本,类似的脚本网上... var a = document.evaluate('//input[

    HTML抽取器Xsoup.zip

    ...同时Xsoup提供全面的XPath解析错误提示。... result = Xsoup.compile("//a/@href").evaluate(document).get(); Assert.assertEquals("https://github.com", result); } 标签:Xsoup

    XML Viewer Plus:强大的XML Viewer-Firefox浏览器的附加组件-开源

    强大的XML Viewer,支持文本/正则表达式和jQuery / CSS,XPath选择器====版本1.2.6-17.06.2019-为xml查看器添加了... XPath的document.evaluate 7.打包### bestzip的局限性-WebExtension仅在允许内容脚本的网站上工作。

    Software Testing and Continuous Quality Improvement

    Document the Plan. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Step 2. Obtain Management Acceptance . . . . . . . . . . . . . . . . . . . . 18 Step 3. Obtain Development ...

    flaming-tribble

    尝试探索为purescript建立绑定。 我目前只是想找出从phantomjs-node模拟以下代码片段: var phantom = require ( '... evaluate ( function ( ) { return document . title ; } , function ( result ) { console .

    xsoup:当jsoup遇到XPath时

    Xsoup 基于Jsoup的XPath选择器。 开始使用: @Test public void testSelect() { ... " &lt;table&gt;&lt;tr&gt;&lt;td&gt;a&lt;/td&gt;&lt;td&gt;b&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;... evaluate(document) . get(); Assert . assertEquals

    chromy:Chromy是用于操作无头Chrome的库。 :beer_mug::beer_mug::beer_mug:

    克罗米 Chromy是用于操作无头Chrome的库。 文档站点: : Chromy与Nightmare.js类似,但有一些区别: 通过Chrome DevTools协议控制Chrome。... return document . querySelectorAll ( '*' ) . length } ) . r

    Learning Word Vectors for Sentiment Analysis

    vectors capturing semantic term–document information as well as rich sentiment content. The proposed model can leverage both continuous and multi-dimensional sentiment information as well as non-...

    PMBOK英文第五版

    consensus, it does not write the document and it does not independently test, evaluate, or verify the accuracy or completeness of any information or the soundness of any judgments contained in its ...

    tosser:在 JavaScript 中评估 CSS calc 表达式

    // Find the element to evaluate against var container = document . body ; // Returns the length in px units (as a string) var px = tosser . evaluateCalc ( 'calc((50% + 10px / 3) * 6)' , { container ...

    ISPRS Test Project on Urban Classification and 3D

    The automated extraction of urban objects from data...order to evaluate techniques for the extraction of various urban object classes. The test data are described in detail in Section 2 of this document.

    A Guide to the Project Management Body of Knowledge

    While PMI administers the process and establishes rules to promote fairness in the development of consensus, it does not write the document and it does not independently test, evaluate, or verify the...

    DataStage IBM

    responsibility to evaluate and verify the operation of any non-IBM product, program, or service. IBM may have patents or pending patent applications covering subject matter described in this document....

    dom-bindings:Riot.js DOM绑定模板引擎

    绑定 用法 import { template , expressionTypes } from '@riotjs/... evaluate : scope =&gt; scope . greeting , } , ] , } ] ) // Mount the template to any DOM node const target = document . getElementById

    CISCO Change Management-Best Practice white_paper

    2.2.1.5 Document the Change Request 2.2.1.6 Create the Request for Change 2.2.1.7 Technical Review and Signoff 2.2.1.8 Review the RFC 12 2.2.1.9 Assess and Evaluate the RFC 2.2.1.10 Authorize the ...

    Mastering Machine Learning with scikit-learn -2017.7.24

    He was worked on a variety of machine learning problems, including automatic speech recognition, document classification, object recognition, and semantic segmentation. An alumnus of the University ...

    NIST SP800-55.pdf

    security protection resources or identify and evaluate nonproductive controls. It explains the metrics development and implementation processes and how metrics can be used to adequately justify ...

    The PMI Guide to Business Analy - PMI

    While PMI administers the process and establishes rules to promote fairness in the development of consensus, it does not write the document and it does not independently test, evaluate, or verify the...

    sensorxplorerinstallation.pdf

    The SensorXplorer TM is a demonstration kit designed to help evaluate Vishay’s digital sensors featured on Vishay’s sensor boards. These boards, along with their respective software modules, can be ...

Global site tag (gtag.js) - Google Analytics