【问题标题】:CasperJS not finding link when queryselector is passed a variable向查询选择器传递变量时CasperJS找不到链接
【发布时间】:2017-08-15 22:35:53
【问题描述】:

我正在尝试使用 casperjs 抓取网页。当我将链接 ID 作为变量传递时,它无法单击链接,但是当我手动输入文本字符串时,它可以工作。

这很好用

console.log(this.evaluate( function() {document.querySelector("#ctl00_ContentPlaceHolder1_Name_Reports1_TabContainer1_TabPanel1_dgReports_ctl03_View").click(); } ));

点击链接失败

var id = "#ctl00_ContentPlaceHolder1_Name_Reports1_TabContainer1_TabPanel1_dgReports_ctl03_View";
console.log(this.evaluate( function() {document.querySelector(id).click(); } ));

一切都完全一样,除了我在第二项中使用了一个变量。

为了完整起见,这里是注释掉变量方法的完整函数

casper.then(function () {
    //var id = "#ctl00_ContentPlaceHolder1_Name_Reports1_TabContainer1_TabPanel1_dgReports_ctl03_View";
    //console.log(this.evaluate( function() {document.querySelector(id).click(); } ));
    console.log(this.evaluate( function() {document.querySelector("#ctl00_ContentPlaceHolder1_Name_Reports1_TabContainer1_TabPanel1_dgReports_ctl03_View").click(); } ));
    console.log("Clicked: " + id);
});

这是我正在寻找的元素

<a id="ctl00_ContentPlaceHolder1_Name_Reports1_TabContainer1_TabPanel1_dgReports_ctl03_View" class="lblentrylink" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$Name_Reports1$TabContainer1$TabPanel1$dgReports$ctl03$View','')">View Report</a>

【问题讨论】:

  • 尝试将id 作为参数传递给函数(您需要声明参数,然后在调用中传递它)。请记住,函数是在不同的上下文中评估的。
  • @jcaron 你这是什么意思?我对JS不是很熟悉。如果我使用console.log(this.evaluate( function(id) {document.querySelector("#" + id).click(); } ));,它仍然会失败。
  • 您仍然需要将id 作为参数传递给evaluate
  • @jcaron 喜欢这个? console.log(this.evaluate( function(id) {document.querySelector("#" + id).click(); }, id )); ?这对我仍然不起作用。
  • 在您的原始帖子中,您的 id 中有 #,请确保您没有两次。也尝试在函数内记录id

标签: javascript phantomjs casperjs


【解决方案1】:

您可以使用以下方法将您的参数传递给casper.evaluate()

casper.then(function () {
  var id = '#ctl00_ContentPlaceHolder1_Name_Reports1_TabContainer1_TabPanel1_dgReports_ctl03_View';

  this.evaluate(function (id) {
    document.querySelector(id).click();
  }, id);

  console.log('Clicked: ' + id);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2016-04-05
    相关资源
    最近更新 更多