封云亭 发表于 2017-4-24 07:58:20

mxTidy

抓取的html不处理一下很容易破坏页面的布局

官网的python封装好像不支持linux,囧

另外找了一个

mxTidy - HTML Tidy for Python

网站
http://www.egenix.com/products/python/mxExperimental/mxTidy/

下载
http://www.egenix.com/products/python/mxExperimental/

文档
http://www.egenix.com/products/python/mxExperimental/mxTidy/mxTidy.pdf

我看了半天文档,居然没有找到,不让他输出
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
的接口
只好自己山寨了一个

from mx import Tidy
def tidy(html):
    html=Tidy.tidy(html,output_xhtml=1,wrap=0)
    begin="<body>"
    return html.strip()
   
print tidy('<div>x<img src="xx"><p>')

<div>x<img src="xx" /></div>

htmltidy 的 python 封装(续)


Qiangning Hong
发送至 我

试过,激活tidy会导致进程crash,没有找到原因。

---------------------------
我一测试果然,不知道是封装烂,还是本身就烂

干脆用原始的版本,搞一个进程外调用吧

wget http://nchc.dl.sourceforge.net/sourceforge/tidy/tidy4aug00.tgz

然后安装,然后

from __future__ import with_statement
import subprocess
import os

def tidy(html):
    with os.tmpfile() as temp:
      with open(os.devnull,"w" ) as null:
            print >>temp,html
            temp.seek(0)
            html=subprocess.Popen(
            ["tidy", "-utf8","-asxhtml"],
            stdin=temp,
            stderr=null,
            stdout=subprocess.PIPE
            ).communicate()
    begin="<body>"
    return html.strip()

tidy("<div>x<a>a")
页: [1]
查看完整版本: mxTidy