【问题标题】:Can XPath be used to search a <script> block?XPath 可以用于搜索 <script> 块吗?
【发布时间】:2015-10-21 12:23:21
【问题描述】:

我在选择各种 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 的方法。有谁知道更多/可以给我一个提示吗?

【问题讨论】:

  • 请发布您的代码。
  • 嘿,我把它编辑得更具体了
  • = 右侧的表达式看起来像 JSON,因此使用 php.net/manual/en/function.json-decode.php 解析它可能比使用正则表达式更好。
  • 当然。假设它是 JSON,然后使用 XPath 将其读取为字符串,然后将其放入 JSON 解析器中。
  • Json decode 是这里的主人。谢谢

标签: javascript php dom xpath selector


【解决方案1】:

你可以试试正则表达式:

preg_match_all("/finalPrice\\":\\"([0-9.]{1,10})\\"/", $page_html, $output_array);

【讨论】:

  • 感谢您的回答,我将如何修改此 sn-p 以仅选择“ID”为 2292 的最终价格?像这样? preg_match_all("/2292\\":"/finalPrice\\":\\"([0-9.]{1,10})\\"/", $page_html, $output_array);
  • 看看这个:preg_match_all("/2292(.*)finalPrice\\":\\"([0-9.]{1,10})\\"/", $input_lines , $output_array);
【解决方案2】:

您可以像这样从对象中读取属性。

var obj = {"2292":{"price":"64.99","finalPrice":"64.99","no_of_servings":"166","178":"27","179":"34"}};
obj['2292']['finalPrice']

【讨论】:

  • 感谢您的回答。我将问题中的 javascript 修改为更具体。对象名称 = productConfig,我在其中搜索的变量是 childProducts。在该 var 内部是一个包含 2292 个产品(4 次)的数组,我尝试将此作为我的查询:productConfig['childProducts']['2290']['finalPrice']) 它没有返回任何内容。你知道我在这里做错了什么吗?
【解决方案3】:

所以我做了什么:使用提供的 XPATH 查询读出脚本。比: strstr 直到我得到我想要的 json 部分。接下来是:PHP 的 json_decode 函数。把它放在一个数组中,而不是在数组中搜索我想要的东西。这是我的解析代码:

        $price_query = $finder->query("//script[contains(.,'finalPrice')]");
        $price_raw = $price_query->item(0)->nodeValue;
        $price_1 = strstr($price_raw, "childProducts");
        $price_2 = str_replace('childProducts":', '', $price_1);
        $price_3 = strstr($price_2, ',"priceFromLabel"', true);     
        $price_data = json_decode($price_3, true);

使用 str str 看起来像废话,但有效。谢谢大家的想法。 json_decode ftw!

【讨论】:

    猜你喜欢
    • 2011-11-03
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多