Python 如何搜索并修正 HTML 标签和属性?
我需要修复所有的 <img>
标签的闭合方式,如下文所示。正确的做法是用 />
来闭合 <img>
,而不是用 >
。
有没有简单的方法可以在这段文字中找到所有的 <img>
标签,并把 >
改成 />
呢?
(如果已经是用 />
闭合的,就不需要做任何操作了)。
还有一个问题,如果 <img>
标签没有指定 "width" 或 "height",那该怎么解决呢?
是下载所有的图片,然后获取相应的宽度和高度属性,再把这些信息加回到字符串中吗?
正确的 <img>
标签是用 />
闭合,并且有有效的宽度和高度。
<a href="http://www.cultofmac.com/daily-deals749-mac-mini-1199-3-0ghz-imac-new-mac-pros/52674"><img align="left" hspace="5" width="150" src="http://s3.dlnws.com/images/products/images/749000/749208-large" alt="" title=""></a>
Apple today unleashed a number of goodies, including giving iMacs and Mac Pros more oomph with new processors and increased storage options. We have those deals today, along with many more items for the Mac lover. Along with the refreshed line of iMacs and Mac Pros, we’ll also look at a number of software deals [...]
<p><a href="http://feedads.g.doubleclick.net/~a/DL_-gOGSR1JMzKDbErt1EG3re3I/0/da"><img src="http://feedads.g.doubleclick.net/~a/DL_-gOGSR1JMzKDbErt1EG3re3I/0/di" border="0" ismap></a><br>
<a href="http://feedads.g.doubleclick.net/~a/DL_-gOGSR1JMzKDbErt1EG3re3I/1/da"><img src="http://feedads.g.doubleclick.net/~a/DL_-gOGSR1JMzKDbErt1EG3re3I/1/di" border="0" ismap></a></p><img src="http://feeds.feedburner.com/~r/cultofmac/bFow/~4/Mq5iLOaT50k" height="1" width="1">
我真的需要在输出中包含 width
和 height
,因为这些会作为其他解析器的输入。而那个解析器要求 <img
标签必须用 />
闭合。我并不是用输出在网页上查看。请给我一个简单的解决方案来实现这一点!
3 个回答
好吧,<img ...> 是正确的 HTML 写法,而 <img .../> 不是。我不知道 HTML5 是怎么说的,但 XHTML 在活着之前基本上就已经死了。
不过,我觉得最简单的方法是用正则表达式:
re.sub(r"<img(.*?)(?<!/)>", lambda m: "<img%s/>" % m.groups()[0], html_code)
至于其他的事情,那就比较复杂了。我会解析代码,把标签加到 img 节点上,然后从抽象语法树(ast)写出 HTML。解析应该可以用 http://code.google.com/p/html5lib/ 来实现。但是为了获取有效的高度和宽度,你需要读取图片(可以用 PIL),这可能不太值得去做。
这个回答在谷歌搜索中仍然是最受欢迎的,可能是因为我对问题理解得不够透彻。
我想要的是一个xml格式的数据导出,而不是html格式的数据导出。
为了提取我需要的数据,并且能够正确地交给其他人,我使用了lxml.html,就像@Tim McNamara提到的那样。
import lxml.html
# read in the file
html_obj = lxml.html.fromstring(raw_html)
# whatever other dom manipulation you need to do
lxml.html.tostring(html_obj, method='xml')
为了简单起见,我会把解析(X)HTML时可能遇到的麻烦问题交给一个专门的库来处理:
这里有一个使用 lxml.html 的简单例子:
import lxml.html
page = """<html>...</html>"""
page = lxml.html.document_fromstring(page)
lxml.html.tostring(page)
lxml.html
有一个非常实用的模块 clean
,它的设计目的是用来去除恶意代码。使用起来也很简单:
from lxml.html.clean import clean_html
clean_html(page)