使用 casperjs 抓取文本节点的最快方法

fastest way to scrape text node with casperjs

本文关键字:方法 节点 casperjs 抓取 取文本 使用      更新时间:2023-09-26

>我有这个结构,我需要从这样的纯文本节点获取文本

<strong><font color="#666666">Phones:</font></strong>
<br>
<br>
<img src="/image/fgh.jpg" title="Velcom" alt="Velcom" style="margin: 2 5 -3 5;">
"+375 29"              //get this
<b>611 77 83</b>      //and this

我尝试使用从chrome控制台复制的XPath

casper.thenOpen('url', function() {
    result = this.getElementInfo(x('//*[@id="main_content"]/table[2]/tbody/tr[17]/td/table/tbody/tr/td[1]/p[1]/text()[3]'));
});
casper.then(function() {
    this.echo(result.text);
});

但它不起作用。另外,当我尝试result.data

console.log(this.getElementInfo(x('//*[@id="main_content"]/table[2]/tbody/tr[17]/td/table/tbody/tr/td[1]/p[1]/text()[3]')));

返回null,但页面中存在此元素,我检查了它

确保您已包含:

var x = require('casper').selectXPath;

如果这仍然不起作用,以下内容将从页面中检索所有文本,然后您可以解析。 为了提高性能,不建议这样做,但如果要分析锚文本,则此方法确实有效。 您将需要稍微修改。

var casper = require("casper").create ({
    waitTimeout: 15000,
    stepTimeout: 15000,
    verbose: true,
    viewportSize: {
        width: 1400,
        height: 768
    },
    onWaitTimeout: function() {
        logConsole('Wait TimeOut Occured');
        this.capture('xWait_timeout.png');
        this.exit();
    },
    onStepTimeout: function() {
        logConsole('Step TimeOut Occured');
        this.capture('xStepTimeout.png');
        this.exit();
    }
});
casper.on('remote.message', function(msg) {
    logConsole('***remote message caught***: ' + msg);
});
casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4');
// vars
var gUrl           = 'WebAddy'; //+++ Update URL
casper.start(gUrl, function() {
  var tPlainText = this.evaluate(function() {
    var bodyText        = document.body;
    var textContent     = bodyText.textContent || bodyText.innerText;
    var tCheck          = textContent.indexOf("Phones:");
    if (tCheck === -1) {
      tPlainText = 'Phone Text Not Found';
        return tPlainText;
    } else {
      // parse text
      var tSplit              = textContent.split('Phones:');
      var tStr                = (tSplit[1]) ? tSplit[1] : '';
      var tPos1               = tStr.indexOf(''); //+++ insert text to stop parse 
      var tDesiredText         = (tPos1 !== -1) ? tStr.substring(0, tPos1) : null;
        return tDesiredText;
    }
  });
  console.log(tPlainText);
});
casper.run();

一个老问题,但我有同样的问题。我需要获得以下文本,所以这是我是如何做到的。

__utils__.getElementByXPath("//bla...bla/following-sibling::node()").textContent;