2

出于几个原因,我从一个脚本中获取输出,该脚本使用一些我不需要的额外 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 去除标签旁边的字符串的所有内容和包含的标签..

4

1 回答 1

3

使用正则表达式删除 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(这是模式的第三组)

于 2013-08-24T10:57:54.417 回答