gpt4 book ai didi

html - 用于从字符串中删除 html 垃圾的 bash 脚本的正则表达式

转载 作者:行者123 更新时间:2023-11-27 22:30:26 25 4
gpt4 key购买 nike

出于多种原因,我从一个脚本中获取输出,该脚本使用一些我不需要的额外 html 代码来抓取 html 页面。

这是我的:

... MY DATA IN A SINGLE ROW FOLLOWED BY ...> <script>function fbs_click() {u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}</script><style> html .fb_share_button { display: -moz-inline-block; display:inline; padding:1px 11px 0 5px; height:15px; border:1px solid #d8dfea; background:url(http://static.ak.facebook.com/images/share/facebook_share_icon.gif?6:26981) no-repeat top right; } html .fb_share_button:hover { color:#fff; border-color:#295582; background:#3b5998 url(http://static.ak.facebook.com/images/share/facebook_share_icon.gif?6:26981) no-repeat top right; text-decoration:none; } </style> <a rel="nofollow" href="http://www.facebook.com/share.php?u=/dizionario/recensi ne.asp?id=11334" class="fb_share_button" onclick="return fbs_click()" target="_blank" style="text-decoration:none;"></a>

也许这个额外的代码可以用 REGEXP 删除,删除标签旁边的字符串的所有内容和包含的标签..

最佳答案

使用正则表达式删除 html 标签(以及脚本和样式)并不总是那么容易,但是由于您正在寻找 bash 方式,您可以使用一个简单的技巧:使用文本浏览器(lynx、链接、w3m),示例:

lynx -dump input.html > output.txt

或者您可以使用内联工具 xidel使用 XPath 查询:

xidel ./input.html --extract "//text()[not(parent::style|parent::script)]"

您也可以尝试使用正则表达式,但它不太安全:

sed 's/<script.*<\/script>\|<style.*<\/style>\|<[^>]*>//g' input.html

(请注意,此正则表达式失败,类似:<script>sfsdfsfsdf</script> CONTENT <script>sdfsdfsdf</script>)

或者您可以使用这个在 html 上下文中更安全的正则表达式:

sed -r 's/<script([^<]|<[^\/]|<\/[^s]|<\/s[^c])*<\/script>|<style([^<]|<[^\/]|<\/[^s]|<\/s[^t])*<\/style>|<[^>]*>//g' input.html

您可以通过在最后一个案例(即 |<[^>]*> )之前添加一个捕获组来轻松保留诸如“a”和“strong”之类的标签:

|(<a ([^<]|<[^\/]|<\/[^a]|<\/a[^>])*<\/a>|<strong([^<]|<[^\/]|<\/[^s]|<\/s[^t]|<\/st[^r])*<\/strong>)

然后通过 $3 更改替换模式(这是第三组图案)

关于html - 用于从字符串中删除 html 垃圾的 bash 脚本的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18417132/

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