【发布时间】: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"}'
-
/<script[^>]*>\s*window\._userData\s*=\s*([\s\S]*?)<\/script>/并用 json 解析
标签: javascript php html regex web-scraping