抓取网页并检索javascript变量


Scrape web page and retrieve javascript variables

我需要抓取一个在内联javascript代码中嵌入javascript数组的网页,例如:

<script>
    var videos = new Array();
    videos[0] = 'http://myvideos.com/video1.mov'; 
    videos[1] = ....
    ....
</script>

什么是最简单的方法来处理这个问题并最终得到这些视频URL的PHP数组?

编辑:所有视频都是.mov扩展名。

这有点复杂,但它只会得到那些真正形式为videos[0] = 'http://myvideos.com/video1.mov'; 的链接

$tmp=str_replace(array("'r","'n"),'',$original,$matches);
$pattern='/'<script'>'s+var' videos.*?(('s*videos'['d+']' '=' .http':'/'/.*?';'s*?)+)(.*?)'<'/script'>/';
$a=preg_match_all($pattern,$tmp,$matches);
unset($tmp);
if (!$a) die("no matches");
$pattern="/videos'['d+']' '=' /";
$matches=preg_split($pattern,$matches[1][0]);
$final=array();
while(sizeof($matches)>0) {
  $match=trim(array_shift($matches));
  if ($match=='') continue;
  $final[]=substr($match,1,-2);
}
unset($matches);
print_r($final);

在OP反馈后,这里是简化版本:

$original=file_get_contents($url);
$pattern='/http':'/'/.*?'.mov/';
$a=preg_match_all($pattern,$original,$matches);
if (!$a) die("no matches");
print_r($matches[0]);

您可以通过使用file_get_contents读取页面,然后使用regex检索URL来获取这些内容。这是我所知道的最简单的方法,尤其是如果你知道视频的文件扩展名的话。示例:

<?php
$file = file_get_contents('http://google.com');
$pattern = '/http:'/'/([a-zA-Z0-9'-'.]+'.[fr|com]+)/i';
preg_match_all($pattern, $file, $matches);
var_dump($matches);