【问题标题】:PHP DOM Get website all scripts srcPHP DOM 获取网站所有脚本src
【发布时间】:2015-12-04 13:10:43
【问题描述】:

我想使用 curl 和 DOM 从网站获取所有脚本 src 链接。

我有这个代码:

$scripts = $dom->getElementsByTagName('script');

foreach ($scripts as $scripts1) {

    if($scripts1->getAttribute('src')) {

        echo $scripts1->getAttribute('src');

    }

}

这个脚本可以完美运行,但是如果网站有这样的脚本标签会发生什么:

<script type="text/javascript">
window._wpemojiSettings = {"source":{"concatemoji":"http:\/\/domain.com\/wp-includes\/js\/wp-emoji-release.min.js?ver=4.2.4"}}; ........
</script>

我还需要获取此脚本 src。我该怎么做?

【问题讨论】:

  • 那你需要写一些代码来找到包含脚本的其他机制
  • 那个&lt;script&gt; 标签没有src 属性。这是一些内联 JavaScript,将变量 _wpemojiSettings 设置为一个对象。
  • 我知道是没有的,这就是我问的原因,因为有的有,有的没有,而是使用一个对象来加载src。如果你们能给我一个从哪里开始的想法。
  • 也许看看WWW:Mechanize 执行Javascript。
  • 有无数种方法可以将脚本文件的 URL 嵌入到 JavaScript 代码中并动态加载它。您需要以某种方式解析/执行 JavaScript 代码并找出 URL 的存储位置。

标签: javascript php dom preg-match


【解决方案1】:

如果您的第一个解析器为空,我会使用正则表达式创建另一个,即:

$html = file_get_contents("http://somesite.com/");

preg_match_all('/<script.*?(http.*?\.js(?:\?.*?)?)"/si', $html, $matches, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($matches[1]); $i++) {
    echo str_replace("\\/", "/", $matches[1][$i]);
}

您可能需要调整正则表达式以适用于不同的网站,但上面的代码应该让您了解您需要什么。


演示: http://ideone.com/Fwf6Mb


正则表达式解释:

<script.*?(http.*?\.js(?:\?.*?)?)"
----------------------------------

Match the character string “<script” literally «<script»
Match any single character «.*?»
   Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the regex below and capture its match into backreference number 1 «(http.*?\.js(?:\?.*?)?)»
   Match the character string “http” literally «http»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
   Match the character “.” literally «\.»
   Match the character string “js” literally «js»
   Match the regular expression below «(?:\?.*?)?»
      Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
      Match the character “?” literally «\?»
      Match any single character «.*?»
         Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “"” literally «"»

正则表达式教程

http://www.regular-expressions.info/tutorial.html

【讨论】:

  • 感谢您的代码,它正在工作,但它会从脚本标签获取所有类型的链接(图像等)。我只需要 .js 文件。就像我做一个 preg_match 来只获取里面有 .js 的链接。
  • 像魅力一样工作,还需要添加 .js?ver=xxx 的版本,我试过这个但不工作 '/
  • 只需在js之后添加.*?
  • 现在给我相同的结果 + 1 个没有 js 的新链接
  • 我已经帮你了,不该轮到你自己动手去发现解决方案,否则你永远学不会。
猜你喜欢
  • 2012-04-19
  • 2019-06-17
  • 2017-07-29
  • 1970-01-01
  • 2016-02-11
  • 1970-01-01
  • 2014-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多