PHP从网页代码里面提取JS变量值及data参数值
通常用于抓取网页,模拟数据提交时
匹配 JavaScript 变量赋值, 提取 data: { ... } 的内容
function get_var($name, $html) { // 匹配 JavaScript 变量赋值
// 匹配 <script> 标签内容
$scriptPattern = "/<script\b[^>]*>([\s\S]*?)<\/script>/i";
preg_match_all($scriptPattern, $html, $scriptMatches);
if (empty($scriptMatches[1])) {
return false; // 未找到 <script> 标签
}
// 遍历所有 <script> 标签内容
foreach ($scriptMatches[1] as $scriptContent) {
// 匹配 JavaScript 变量赋值
$pattern = "/\b(?:var|let|const)?\s*" . preg_quote($name, '/') . "\s*=\s*(.*?);/s";
preg_match($pattern, $scriptContent, $matches);
if (!empty($matches[1])) {
// 去除值两侧的空格和引号
$value = trim($matches[1]);
$value = trim($value, "'\""); // 去除单引号或双引号
// 验证值是否为字符或数字
if (preg_match('/^[a-zA-Z0-9\.\-\_]+$/', $value)) {
return $value;
}
}
}
return false; // 未找到变量或变量值不符合要求
}
function get_js_data($html) { //Js代码中提取 data: { ... } 的内容
// 移除所有注释(单行和多行)
$html = preg_replace("/\/\/.*?\n/", "\n", $html); // 移除单行注释
$html = preg_replace("/\/\*[\s\S]*?\*\//", "", $html); // 移除多行注释
// 匹配 data: { ... } 的内容(支持跨行和嵌套对象)
$pattern = '/data\s*:\s*\{((?:[^{}]*|(?R))*)\}/s';
preg_match($pattern, $html, $matches);
if (empty($matches[1])) {
return false; // 未找到 data 内容
}
$dataContent = trim($matches[1]);
// 标准化键名和值
$dataContent = preg_replace_callback(
'/(\w+)\s*:/',
function ($m) { return '"' . $m[1] . '":'; }, // 键名加双引号
$dataContent
);
// 处理单引号字符串
$dataContent = preg_replace("/'([^']*)'/", '"$1"', $dataContent);
// 处理特殊值表达式(如 jQuery 选择器)
$dataContent = preg_replace_callback(
'/:\s*([^,}\n]+)/',
function ($m) {
$value = trim($m[1]);
// 处理变量和函数表达式
if (preg_match('/^\$\(|^[a-zA-Z_]/', $value)) {
return ': "' . addslashes($value) . '"'; // 转为带转义的字符串
}
return ': ' . $value;
},
$dataContent
);
// 修复尾部逗号问题
$dataContent = preg_replace('/,\s*}/', '}', $dataContent);
// 尝试解析为 PHP 数组
$dataArray = json_decode('{' . $dataContent . '}', true);
if (json_last_error() !== JSON_ERROR_NONE) {
return false; // 解析失败
}
return $dataArray;
}
评论
发表评论: