gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:13:11 25 4
gpt4 key购买 nike

我试图在页面完全加载后单击图像链接。图像链接嵌套在 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 并不关心元素的类型,因此如果 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();

关于javascript - 选择网页上的超链接并使用 CasperJS 将生成的网页内容存储在文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34059226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com