【问题标题】:Regular Expression to Extract Javascript Object from Scraped HTML从抓取的 HTML 中提取 Javascript 对象的正则表达式
【发布时间】:2016-10-13 17:18:07
【问题描述】:

我有一个整页的 HTML 抓取,其中有很多标记,包括 HTML/CSS/JS 代码。

下面的示例(剥离的内容)

<p>blah blah blah html</p>
<script type="text/javascript">window._userData ={"country_code": "PK", "language_code": "en",user:[{"user": {"username": "johndoe", "follows":12,"biography":"blah blah blah","feedback_score":99}}],"another_var":"another value"} </script>
<script> //multiple script tags can be here... </script>
<p>blah blah blah html</p>

现在我想提取 window._userData 中的对象,然后如果可能的话,将提取的字符串转换为 PHP 对象/数组。

我尝试了一些在 SO 上找到的正则表达式,但无法正常工作。

我在这里也试过类似的答案Regular expression extract a JavaScript variable in PHP

谢谢

【问题讨论】:

  • 您要提取的对象不正确。
  • @splash58 我已经添加了缺少的 } ,感谢您的评论,请问有什么解决方案吗?
  • 此外,它不能包含空格,并且必须将所有键放在引号中 - `{"country_code":"PK","language_code":"en","user":[{"user": {"username": "johndoe","follows":12,"biography":"blah blah blah","feedback_score":99}}],"another_var":"another value"}'
  • /&lt;script[^&gt;]*&gt;\s*window\._userData\s*=\s*([\s\S]*?)&lt;\/script&gt;/ 并用 json 解析

标签: javascript php html regex web-scraping


【解决方案1】:

通过正则表达式查找

preg_match('/\bwindow\._userData\s*=(.+)(?=;|<\/script)/', $html, $m);

解码

json_decode(trim($m[1]), true);

但在您应该在该 html 中生成正确的 json 之前。

【讨论】:

  • 这是正确的答案,但是当脚本标签包含多个 JS 对象和/或对象包含带有; 的字符串时,您仍然会遇到问题。如果你能排除它会起作用。编辑:JS 不是常规语言,因此this answer applies
  • @JohannesStadler 如果 json 包含 ; 或 EOL,这确实是个问题,我不知道如何解决
  • 我认为使用正则表达式是不可能的。 Js 不是常规语言,所以正则表达式有其局限性。
  • @JohannesStadler Yuo 是对的。不幸的是,我不知道任何解析 js 的库,但 js 本身:)。
猜你喜欢
  • 2018-10-17
  • 2021-04-14
  • 1970-01-01
  • 2018-02-03
  • 2010-09-15
  • 2022-11-18
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
相关资源
最近更新 更多