2016-09-26 70 views
0

我正在尝试获取span._Rnb.fmob_pr.fac-l中的文本。我相信这是股票报价的选择者。现在它只是返回控制台open success跳过一行或2然后退出。使用phantomjs获取来自谷歌的股票报价

var webPage = require("webpage"); 
var page = webPage.create(); 
var url = "https://www.google.com/search?q=goog+stock" 

page.open(url, function(status){ 
    console.log("open", status) 
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function(status){ 
     // console.log($) 
     var price = page.evaluate(function(){ 
      return $("span._Rnb").text() 
      // return $(".kno-rdesc").find("span").text() 
      // return $("._Rnb").text(); 
      // return document.title  
      // return $(document).find("title").text() 
     }) 
     console.log(price) 
     phantom.exit() 
    }) 
}) 

我不知道该如何调试。我做了console.log($),我什么都没有。

我能够获得页面上的h3链接标签。我想知道为什么我无法获得股票报价。

+0

您使用哪个PhantomJS版本?请注册onConsoleMessage,onError,onResourceError,onResourceTimeout事件([Example](https://gist.github.com/artjomb/4cf43d16ce50d8674fdf#file-1_phantomerrors-js))。也许有错误。 Kepp记住PhantomJS中的Google页面与您的桌面浏览器不同。打印页面内容以查看您的需求。 –

+0

既然你说“打印页面内容”我假设做这样的事情会好吗? 'var content = page.content; fs.write(路径,内容,“w”)'。我在文档中搜索了“_Rnb”,但都没有出现。它看起来像股票报价是以“表格格式”。格式不好。现在我需要选择该项目。希望它会起作用。谢谢。我不知道会有什么大不同,就像在“打印”版本中它是一个'table' –

回答

-3

page.evaluate是一个异步函数。这意味着它在函数实际发生之前立即返回。这是合乎逻辑的,因为页面需要时间来渲染。 但是,您的console.log(price),更重要的是,phantom.exit()立即发生。

最简单的解决方案是将console.logphantom.exit置于长时间(5-10秒)以让页面正确评估。

更合适的解决方案将是某种投票,甚至事件从评估页面内部传递到外部的phantom.js代码 - 随时进行实验。

+0

不,$(“span._Rnb”)。text()是同步的,所以整个页面.evaluate'调用将是同步的。 –

0

选择器return $("table:nth-of-type(1) tbody > tr > td > span > b").eq(0).text()工作。

page.open(url, function(status){ 
    console.log("open", status) 
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function(status){ 
     var price = page.evaluate(function(){ 
      return $("table:nth-of-type(1) tbody > tr > td > span > b").eq(0).text() 
     }) 
     console.log(price) 
     phantom.exit() 
    }) 
})