Select 网页上的超链接并使用 CasperJS 将结果网页的内容存储在文本文件中

Select a hyperlink on webpage and store the content of resulting webpage in text file using CasperJS

我试图在页面加载后点击图片 link completely.The 图片 link 嵌套在 div 标签中,如下所示

<section id="A">
    <div class="B">
        <div>
            <div>
                <a href="url" class="C">
                    <img src="http://www.example.com/xyz.jpg">
                </a>
            </div>
        </div>                      
    </div>                                   
</section>  

我正在尝试加载图像 link 并将其内容写入文本文件,但它无法使用下面给出的代码

var fs = require('fs');
var casper = require('casper').create();
casper.start('http://www.example.com/');

var selector = "A > a:first-child";
casper.waitUntilVisible(selector)
    .thenClick(selector)
    .wait(10000)
    .waitTimeout = 90000 
    .then(function(){
        fs.write('myfile.txt', this.getHTML(), 'w');
    });

casper.run();

x > y 对于 CSS 选择器意味着 y 匹配的元素是 x 匹配的元素的 child。根据您的标记,A 中的 A > a:first-child 不是有效的选择器。我怀疑你想使用 id 的 A,它应该是 #A > a:first-child,但是 a 不是 #A 的 child。

您需要使用后代操作(space):#A a:first-child 或完全限定选择器:#A > div.B > div > div > a:first-child。请注意 :first-child 不关心元素是哪种类型,因此如果 a 不是第一个元素它是 parent,那么它不会匹配任何内容。你可以使用 a:first-of-type.

此外,此代码将产生 TypeError,因为 then 不是数字 (90000) 上的函数。当您以这种方式设置 属性 时,您不能链接某些东西。您必须在 then 函数或回调开始之前或内部设置 waitTimeout

尝试:

var fs = require('fs');
var casper = require('casper').create();
casper.start('http://www.example.com/');

var selector = "#A > div > div > div > a:first-of-type";
casper.waitUntilVisible(selector)
    .thenClick(selector)
    .wait(10000)
    .then(function(){
        fs.write('myfile.txt', this.getHTML(), 'w');
    });

casper.run();