简体   繁体   English

使用CasperJS删除DOM元素

[英]Removing a DOM element using CasperJS

Okay basically I have a post: 好的,基本上我有一个帖子:

<div class=post>
  <div class=content></div>
  <div class=content-meta></div>
</div>

thats the prototype of it to help explain 多数民众赞成在其原型,以帮助解释

so what I want to do is use some JS to basically delete or hide the div 'content-meta' 所以我想做的是使用一些JS基本上删除或隐藏div'content-meta'

Using JQuery I have: 使用JQuery我有:

$('.content-meta').remove();

however when I am using CasperJS I am a little puzzled as how I should implement this code. 但是,当我使用CasperJS时,我对如何实现此代码感到有些困惑。

I am looking to manipulate a post prior to screen capturing it (the screencapture part works fine) 我想在屏幕捕获之前操纵帖子(screencapture部分工作正常)

Heres the code (URL's OMITTED) I have been testing with, It picks up the class just fine, but I have no idea where/how to execute the Jquery to remove the detected element prior to screen capture: 这是我一直在测试的代码(URL省略),它可以很好地拾取类,但是我不知道在屏幕捕获之前在哪里/如何执行Jquery来删除检测到的元素:

casper.start('http://pageurl.com/XYZ', function() {

if (this.exists('.content-meta')) {
    this.echo('found .content-meta', 'INFO');
} else {
    this.echo('.content-meta not found', 'ERROR');
}
this.captureSelector('resultingcapture.png', '.post');
});

casper.run();

TL;DR How do you execute JS/Jquery from within a CasperJS function? TL; DR如何在CasperJS函数中执行JS / Jquery?

For execute javascript code from CasperJS, You have to use evaluate() method 为了从CasperJS执行javascript代码,您必须使用评估()方法

The evaluate() method as a gate between the CasperJS environment and the one of the page you have opened; validate()方法是CasperJS环境和您打开的页面之一之间的门户; everytime you pass a closure to evaluate(), you're entering the page and execute code as if you were using the browser console. 每次将闭包传递给valuate()时,您都在进入页面并执行代码,就像使用浏览器控制台一样。

Your code should be something like this: 您的代码应如下所示:

var casper = require('casper').create();

casper.start('http://pageurl.com/XYZ', function() {

   if (this.exists('.content-meta')) {

       this.echo('found .content-meta', 'INFO');

       //evaluates an expression in the current page DOM context.
       this.evaluate(function(){
          //delete div 'content-meta'
          $('.content-meta').remove();
       });

       this.then(function(){
           this.captureSelector('resultingcapture.png', '.post');
       });

  } else {
      this.echo('.content-meta not found', 'ERROR');
  }
});

casper.run();

Note: This code is going to run only if the webcontext includes jQuery, otherwise you have to remove the div using just javascript. 注意:仅当webcontext包含jQuery时,此代码才会运行,否则,您仅需使用javascript删除div。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM