【问题标题】:Scraping <script> tag with certain keyword using Simple HTML Dom Parser使用 Simple HTML Dom Parser 使用特定关键字抓取 <script> 标记
【发布时间】:2015-10-25 23:45:35
【问题描述】:

我正在尝试使用 Simple HTML Dom 从一组网页中抓取 &lt;script&gt; 标记。起初,我通过提供我需要的标签的数字顺序来抓取它:

$script = $html->find('script', 17); //The tag I need is typically the 18th <script> tag on the page

我开始意识到顺序会因页面而异(而且这不是一种可扩展的方式,因为它可能随时更改)。我怎样才能在我需要的标签中搜索关键字,然后拉回完整的标签?例如,我需要的标签总是包含字符串“PRODUCT_METADATA”。

提前感谢您的任何想法!

【问题讨论】:

  • 将 Xpath 与 simpleXML aor DomDocument 一起使用

标签: javascript php parsing dom simple-html-dom


【解决方案1】:

我最终使用以下代码在所有脚本标签中搜索我的关键字:

$scripts = $html->find('script');
    foreach($scripts as $s) {
        if(strpos($s->innertext, 'PRODUCT_METADATA') !== false) {
            $script = $s;
        }
    }

【讨论】:

    【解决方案2】:

    它可以工作,但对我来说,我试图找到一个隐藏在脚本标签中的 csrf 令牌,起初无法让它工作,所有得到的都是NULL

    我的解决方案是脚本s上的use explode(),非常重要的是记住-&gt;innertext,否则你无法获得string

    我很幸运,令牌是用双引号括起来的,所以很容易得到它。

    我的最终代码如下所示:

    $scripts = $html->find('script');
    foreach($scripts as $s) {
        if (strpos($s->innertext, 'csrf_token') !== false) {
            $script_array = explode('"', $s->innertext);
            $token = $script_array[1];
            break;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-08
      • 2016-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 2012-08-12
      相关资源
      最近更新 更多