繁体   English   中英

通过Web Scraping提取JavaScript变量值

[英]Extracting JavaScript Variable Values via Web Scraping

对于公司项目,我需要使用PHP和JavaScript(包括jQuery)创建一个Web抓取应用程序,该应用程序将从客户网站的每个页面中提取特定数据。 抓取应用程序需要为每个页面获取两种类型的数据:1)确定是否存在具有特定ID的某些HTML元素,以及2)提取特定JavaScript变量的值。 每个页面上的JS变量名称都相同,但值通常不同。

我相信我知道如何获得第一个数据要求:使用PHP file_get_contents()函数获取每个页面的HTML,然后使用JavaScript / jQuery来解析该HTML并搜索具有特定ID的元素。 但是,我不确定如何获取第二个数据 - JavaScript变量值。 甚至在每个页面的HTML中都找不到JavaScript变量; 相反,它可以在链接到页面的外部JavaScript文件中找到。 即使JavaScript嵌入在页面的HTML中,我也知道file_get_contents()只会提取JavaScript代码(和其他HTML)而不是任何变量值。

任何人都可以建议一个很好的方法来获得给定网站的每个页面的变量值吗?

编辑:只是为了澄清,我需要在JavaScript代码运行后的JavaScript变量的值。 这样的事情甚至可能吗?

你说在执行JS之后你需要变量的值。 我假设它总是相同的JS,只是初始变量值是变化的东西。 最好的办法是将JS移植到PHP,它允许您提取初始的JS变量值,然后假装您执行了JS。

这是一个从JavaScript中提取变量值的函数:


/**
 * extracts a variable value given its name and type. makes certain assumptions about the source,
 * i.e. can't handle strings with escaped quotes.
 * 
 * @param string $jsText    the JavaScript source
 * @param string $name      the name of the variable
 * @param string $type      the variable type, either 'string' (default), 'float' or 'int'
 * @return string|int|float           the extracted variable value
 */
function extractVar($jsText, $name, $type = 'string') {
    if ($type == 'string') {
        $valueMatch = "(\"|')(.*?)(\"|')";
    } else {
        $valueMatch = "([0-9.]+?)";
    }

    preg_match("/$name\s*\=\s*$valueMatch/", $jsText, $matches);
    if ($type == 'string') {
        return $matches[2];
    } else if ($type == 'float') {
        return (float)$matches[1];
    } else if ($type == 'int') {
        return (int)$matches[1];
    } else {
        return false;
    }
}

大概这是不可能的,因为它看起来很简单,但如果它是你的 .js你试图检测,为什么不只是有.js通过刮到页面做一些可检测的东西?

使用js在某处填充这样的标签(通过element.innerHTML,大概):

<span><!--Important js thing has been activated!--></span>.   

编辑:或者,也许使用document.write,如果脚本需要可检测onload

你不能使用将被发送到客户端的js脚本,并且该脚本将信息发送到您的服务器吗?

您可以使用Zombie.js节点(JS)库: http://zombie.labnotes.org/

它可以单击链接,遍历dom树,并且应该能够解析JS,因为它是运行它的JavaScript。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM