在网页上选择一个超链接,并使用CasperJS将生成的网页内容存储在文本文件中

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

本文关键字:CasperJS 网页内容 文件 文本 存储 选择 网页 超链接 一个      更新时间:2023-09-26

我正在尝试在页面完全加载后单击图像链接。图像链接嵌套在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>  

我正在尝试加载图像链接并将其内容写入文本文件,但它不适用于下面给出的代码

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();
CSS选择器的

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

您需要使用子体操作(这是一个空格):#A a:first-child或完全限定选择器:#A > div.B > div > div > a:first-child。请注意,:first-child并不关心元素是哪种类型,所以如果a不是它的父元素的第一个元素,那么它将不匹配任何内容。您可以使用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();