问题描述
我是javascript/phantomjs/casperjs的初学者(只学习了几天),但是我一直在使用这张svg图来抓取数据.
I am a very beginer in javascript/phantomjs/casperjs (like only several days of learning) but I am stuck with this svg graph I am trying to scrap data from.
我试图使用casperjs代码从SVG对象访问d="M20,331.37,331.37,21.40...."
元素,并写入控制台和txt文件(或CSV).我尝试以下代码:
I am trying to access the d="M20,331.37,331.37,21.40...."
element from an SVG object using a casperjs code, and write in the console and a txt file (or CSV). I try the following code:
var casper = require('casper').create({
pageSettings: {
loadImages: true,
loadPlugins: true,
userAgent: 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
}
});
//First step is to open baidu.html
casper.start().thenOpen("file:///baidu.html", function() {
console.log("Baidu website opened");
this.wait(6000);
});
casper.then(function() {
var dataFromGraph = this.getElementsAttribute(require('casper').selectXPath('//*[@id="trend"]/svg/path[6]'),"d");
this.echo(dataFromGraph);
require('fs').write("data_graph.txt", dataFromGraph,'w');
});
casper.run();
但是没有任何效果.我得到NULL
元素或空结果.这是我尝试的所有其他代码:
But nothing worked. I get NULL
element or empty result.This is all the other code I try:
var dataFromGraph = this.fetchText(require('casper').selectXPath('//*[@id="trend"]/svg/path[6]/d'));
var dataFromGraph = this.getElementsAttribute(require('casper').selectXPath('//*[@id="trend"]/svg/path[6]'),"d") //,"d")
var dataFromGraph = this.getElementInfo(require('casper').selectXPath('//*[@id="trend"]/svg/path[6]'))
var dataFromGraph = this.fetchText("#trend > svg > path");
我有对象的Xpath和选择器,但是我不确定如何访问它.这是我要剪贴的元素的图片.
I have the Xpath and the selector of the object but I am not sure how to acces it. Here is a picture of the element I want to scrap.
由于我要剪贴的网站需要密码,因此这是我从中保存的HTML文件 https://ufile.io/5y9g2 .
As the website I want to scrap need a password, this is the HTML file that I save from it https://ufile.io/5y9g2.
我要剪贴的元素是此处图形背后的数据.
The element I want to scrap is the data behind the graph here.
任何帮助将不胜感激.
推荐答案
我稍微修改了脚本,现在可以了.检查下面的代码段.
I reworked your script a bit and now it works. Check the snippet below.
var fs = require('fs');
var casper = require('casper').create();
casper.start().thenOpen("http://localhost:8001/baidu.html", function() {
console.log("Baidu website opened");
});
casper.then(function() {
var graphData = this.evaluate(function() {
return document.querySelector('#trend > svg > path:nth-child(11)').getAttribute('d')
});
this.echo(graphData);
fs.write("data_graph.txt", graphData,'w');
});
casper.run();
希望有帮助!
这篇关于使用casperjs从SVG对象访问'd'元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!