如何为匹配html中的内容制作正确的正则表达式?

2024-09-30 05:17:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用regexr生成正则表达式,但无法匹配任何内容

我编写了这样的正则表达式/脚本>;'

我有这样的模板结构:

<!DOCTYPE html> 
<html lang="en-PH" dir="ltr"> 
<head> … </head> 
<body class="is_full PdpV4"> 
<script> This one script which I should get </script>
 <script> window.dataLayer = window.dataLayer || []; dataLayer.push({"feature_test":"VariableControl:1"}); dataLayer.push({"feature_set":"Control"}); 
</script> 
<script>....</script> 
<script> … </script>
 </body> 
</html>

我需要得到第一个脚本/剧本

<script>
    dataLayer = [
        {
            "agent_id": 558921,
            "agent_name": "The City Townhouse",
            "attributes": {
                "agent_ratings_enabled": 0,
                "approved": 1,
                                "attribute_set_id": 1,
                                "categories": JSON.parse("[15,19]"),
                "indoor_features": ["Balcony","Maid's room"],
                "is_agent": 1,
                "listing_type": "Classifieds",
                "other_features": [],
                "outdoor_features": ["Garage"],
                "price_formatted": "₱ 11,300,000 ",
                "price_not_shown": false,
                "seller_is_trusted": 1,
                "show_listing_address": 1,
                "show_mobile": 1
        }
    ];
</script>

我需要把所有东西都放在标签里。非常感谢


Tags: 脚本idishtmlscriptbodywindowpush
2条回答

首先,Paul说,不要使用正则表达式来解析HTML

第二,我不建议这样做,但是如果您真的出于任何原因想要这样做,这个正则表达式将匹配<script>..</script>标记内部的字符:

(?<=<script>).*(?=<\/script>)

你已经被警告了

避免使用正则表达式解析HTML。A seminal stack overflow answer explains why

相反,您应该使用像html5lib这样的包来解析HTML并提取<script>元素的内容,然后从中解析出您想要的内容。这意味着您只需要查看JavaScript代码,这应该是一项简单得多的任务

相关问题 更多 >

    热门问题