php如何抓取网页数据(你不能只使用Python,您需要一个JavaScript引擎(图))

优采云 发布时间: 2022-01-12 16:07

  php如何抓取网页数据(你不能只使用Python,您需要一个JavaScript引擎(图))

  你不能只使用 Python。你需要一个像 PhantomJS 这样的 JavaScript 引擎 API

  使用 Phantom,很容易设置所有页面内容、静态和动态 JavaScript 内容的 Web 抓取(如您的情况下的 Ajax 调用结果)。实际上,您可以执行类似的操作(这是一个 node.js + phantom.js 示例)

  /*

* Register Page Handlers as functions

{

onLoadStarted : onLoadStarted,

onLoadFinished: onLoadFinished,

onError : onError,

onResourceRequested : onResourceRequested,

onResourceReceived : onResourceReceived,

onNavigationRequested : onNavigationRequested,

onResourceError : onResourceError

}

*/

registerHandlers : function(page, handlers) {

if(handlers.onLoadStarted) page.set('onLoadStarted',handlers.onLoadStarted)

if(handlers.onLoadFinished) page.set('onLoadFinished',handlers.onLoadFinished)

if(handlers.resourceError) page.set('onResourceError', handlers.resourceError)

if(handlers.onResourceRequested) page.set('onResourceRequested',handlers.onResourceRequested)

if(handlers.onResourceReceived) page.set('onResourceReceived',handlers.onResourceReceived)

if(handlers.onNavigationRequested) page.set('onNavigationRequested',handlers.onNavigationRequested)

if(handlers.onError) page.set('onError',handlers.onError)

}

  此时,您可以完全控制页面中发生的事情以及何时需要下载,例如:

  ^{pr2}$

  如您所见,您可以定义页面处理程序并控制该页面上加载的流和资源。所以在获取整个页面源之前,可以确保所有数据都准备好并设置好,例如:

  var Parser = {

parse : function(page) {

var onSuccess = function (page) { // page loaded

var pageContents=page.evaluate(function() {

return document.body.innerText;

});

}

var onError = function (page,elapsed) { // error

}

page.evaluate(function(func) {

return func(document);

}, function(dom) {

return true;

});

}

} // Parser

  在这里可以看到 onSuccess 回调中加载的整个页面内容:

  var pageContents=page.evaluate(function() {

return document.body.innerText;

});

  该页面直接来自 Phantomjs,如下代码片段所示:

  phantom.create(function (ph) {

ph.createPage(function (page) {

Parser.parse(page)

})

},options)

  当然,这是针对您和您对 Node.js + Phantom 可以做什么的想法,结合起来超级强大。存在

  可以在 Python 环境中运行 phantomjs,调用它

  try:

output = ''

for result in runProcess([self.runProcess,

self.runScript,

self.jobId,

self.protocol,

self.hostname,

self.queryString]):

output += '' + result

print output

except Exception as e:

print e

print(traceback.format_exc())

  在哪里使用子进程 Popen 执行二进制文件:

  def runProcess(exe):

p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

while(True):

retcode = p.poll() #returns None while subprocess is running

line = p.stdout.readline()

yield line

if(retcode is not None):

break

  当然在这种情况下要运行的进程是node.js

  self.runProcess='node'

  使用您需要的参数作为参数。存在

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线