Phantomjs加载与Chrome不同的页面

时间:2018-08-03 22:16:12

标签: javascript phantomjs screen-scraping

我正在尝试从以下链接下载html:

http://matchhistory.na.leagueoflegends.com/en/#match-details/TRLH3/1000430019?gameHash=a5e39c76a8e91ba9&tab=stats

当我在Chrome中打开文件时,它将与我要下载到html中的所有数据进行匹配。我想用phantomjs打开这些页面,但是它们不加载相同的页面吗?我正在使用以下代码对phantomjs加载的屏幕截图。这只是主要的比赛历史记录页面:http://matchhistory.na.leagueoflegends.com/en

var page = require('webpage').create();
var url="http://matchhistory.na.leagueoflegends.com/en/#match-details/TRLH3/1000430019?gameHash=a5e39c76a8e91ba9&tab=stats";
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';

page.open(url, function(status) {

  if (status !== 'success') {
     console.log('Unable to access network');
  }

 setTimeout(function (){page.render('mh.png');},1000);
 setTimeout(function (){phantom.exit();},1200);
  });

我不确定为什么他们要渲染两种不同的东西。如何让pahntomjs呈现相同的东西?

预先感谢

2 个答案:

答案 0 :(得分:0)

您的http链接可能已重定向到https。我的猜测是phantom.js在重定向中没有保留片段标识符(#match-details)或其后的任何内容,这就是为什么要获取主页http://matchhistory.na.leagueoflegends.com/en

的原因

要解决您的问题,请使用带有https的链接,该链接将起作用,因为您不会被重定向。

var url="https://matchhistory.na.leagueoflegends.com/en/#match-details/TRLH3/1000430019?gameHash=a5e39c76a8e91ba9&tab=stats";

答案 1 :(得分:0)

正如@ andrew-lohr所指出的,这是因为PhantomJS在处理重定向时会删除该片段。发生了一个问题(https://github.com/ariya/phantomjs/issues/12192)并创建了修复请求(https://github.com/ariya/phantomjs/pull/14941),但由于PhantomJS暂停了开发(https://github.com/ariya/phantomjs/issues/15344),这些问题尚未发布。

另一种方法是使用Puppeteer(https://github.com/GoogleChrome/puppeteer),其中有一个有关如何捕获屏幕截图的用法示例。

对于您而言,这就像安装Puppeteer一样简单:

npm install puppeteer

然后将您的代码更新为:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('http://matchhistory.na.leagueoflegends.com/en/#match-details/TRLH3/1000430019?gameHash=a5e39c76a8e91ba9&tab=stats');
  await page.screenshot({path: 'mh.png'});
  await browser.close();
})();

,然后通过node而不是phantomjs运行代码:

node <filename>.js

Puppeteer站点提供了有关可配置内容(查看端口等)的更多信息。