我擅长选择各种 HTML 内容。因此,我充满信心地创建了一些应该提取网站内容的代码,我偶然发现了一些奇怪的 JavaScript 代码,其中源代码将其价格放入其中。
<script>
var productConfig = {"attributes":{"178":{"id":"178","code":"bp_flavour","label":"Smaak","options":[{"id":"28","label":"Aardbeien","oldPrice":"0","products":["2292","2294","2296","2702"]}
....更多的乱码,每个产品变体超过 4 个:(就像这样 80 个不同的行:)
,"childProducts":{
"2292":"price":"64.99","finalPrice":"64.99","no_of_servings":"166","178":"27","179":"34"},
"2292":"price":"17.99","finalPrice":"17.99","no_of_servings":"33","178":"28","179":"25"}
}
</script>
显然2292是手头产品的id。我想读出“finalPrice”。
我的 PHP 代码:
$file = $this->curl_get_file_contents($url);
$doc = new DOMDocument();
@$doc->loadHTML($file);
$doc->preserveWhiteSpace = false;
$finder = new DomXPath($doc);
$price_query = $finder->query("//script[contains(.,'finalPrice')]");
$price_raw = $price_query->item(0)->nodeValue;
但是我的查询 //script[contains(.,"finalPrice")]
爆炸了整个脚本,我无法找到一种方法来更深入、更具体地挖掘 JavaScript。有谁知道更多/可以给我提示吗?
最佳答案
您可以尝试正则表达式:
preg_match_all("/finalPrice\\":\\"([0-9.]{1,10})\\"/", $page_html, $output_array);
关于javascript - XPath 可以用来搜索 <script> block 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718783/