gpt4 book ai didi

html - 使用 AWK 解析 HTML

转载 作者:行者123 更新时间:2023-12-04 16:16:48 25 4
gpt4 key购买 nike

我有以下 HTML 结构,想使用 awk 从中提取数据。

<body>
<div>...</div>
<div>...</div>
<div class="body-content">
<div>...</div>
<div class="product-list" class="container">
<div class="w3-row" id="product-list-row">
<div class="w3-col m2 s4">
<div class="product-cell">
<div class="product-title">Product A</div>
<div class="product-price">100,56</div>
</div>
</div>
<div class="w3-col m2 s4">
<div class="product-cell">
<div class="product-title">Product B</div>
<div class="product-price">200,56</div>
</div>
</div>
<div class="w3-col m2 s4">
<div class="product-cell">
<div class="product-title">Product C</div>
<div class="product-price">300,56</div>
</div>
</div>
<div class="w3-col m2 s4">
<div class="product-cell">
<div class="product-title">Product D</div>
<div class="product-price">400,56</div>
</div>
</div>
</div>
</div>
</div>
</body>

我想要的结果如下。

100,56
200,56
300,56
400,56

我正在试验以下 awk 脚本(我知道选择 product-price 两次是没有意义的,我正要修改这个脚本)

awk -F '<[^>]+>' 'found { sub(/^[[:space:]]*/,";"); print title $0; found=0 } /<div class="product-price">/ { title=$2 } /<div class="product-price">/  { found=1 }'

但它给了我结果

100,56                </div>
200,56 </div>
300,56 </div>
400,56 </div>

我以前从未使用过awk,所以不能只弄清楚这里有什么问题或如何修改上面的代码。你会怎么做?

最佳答案

根据您展示的样本/尝试,请尝试关注 awk代码。

awk -F"[><]" '{gsub(/\r/,"")} /^[ \t]+<div[ \t]+class="product-price">.*<\/div>/{print $3}' Input_file

说明: 为以上添加详细说明。这仅用于运行代码的解释目的,请使用上面的代码。

awk -F"[><]" '      ##Starting awk program from here and setting field separator as ><
{gsub(/\r/,"")} ##Substituting control M chars at last of lines.
/^[ \t]+<div[ \t]+class="product-price">.*<\/div>/{ ##checking condition if line starts
##from space followed by <div class=product-price"> till div close tag.
print $3 ##printing 3rd column here.
}
' Input_file ##Mentioning Input_file name here.

将正则表达式更改为 /^[ \t]+<div[ \t]+class根据埃德在评论中的建议。此外,专家总是建议使用 xmlstarlet/xml 感知工具,以防有人在他们的系统中使用。

关于html - 使用 AWK 解析 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68153733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com