tidy可以整理HTML但不动里面的JS代码。prettier可以整理JS代码,它能不能整理HTML+JS呢?
我写完两个程序后才发现原来可以啊。不过还是把破程序贴出来吧,再说也许发现了prettier的一个bug.
get-js.py

from bs4 import BeautifulSoup as BS import sysbs = BS(open(sys.argv[1], 'r'), 'html.parser') n = 0 for t in bs.find_all('script'):s = t.stringif s is None: continuewith open(f'{n:02d}.js', 'w') as f:print(s, file=f, end='')n += 1
rm-js.py

from html.parser import HTMLParser import sysclass ScriptRemover (HTMLParser):T = 'script'def __init__(m):super().__init__(); m.in_script = False@staticmethoddef ta(t, a):s = '<' + tif len(a): s += ' ' + ' '.join(f'{k}="{v}"' for k,v in a)return sdef handle_starttag(m, t, a):print(f'{m.ta(t,a)}>', end='')if t.lower() == m.T: m.in_script = Truedef handle_endtag(m, t):print(f'</{t}>', end='')if t.lower() == m.T: m.in_script = Falsedef handle_data(m, data):if not m.in_script: print(data, end='')def handle_startendtag(m, t, a): print(f'{m.ta(t,a)}/>', end='')ScriptRemover().feed(sys.stdin.read())
JS里裸放个JSON,prettier说语法错误。该JSON用别的工具们验证没问题,改成形如x={"age":0},prettier也不报错了。
# apt install tidy
# man tidy; -w 代表width
# apt install nodejs npm
# npm install -g prettier -g表示global,为所有用户安装
# 没有manual, -h -c --check -w --write
浏览器不会把<script>作为script对待,而是作为普通文本显示<script>
BeautifulSoup(), param features: Desirable features of the parser to be used. This may be the name of a specific parser ("lxml", "lxml-xml", "html.parser", or "html5lib") or it may be the type of markup to be used ("html", "html5", "xml"), 实测"html"不行,"html.parser"可以。
BeautifulSoup.find_all(self, name=None, attrs={}, recursive=True, string=None, limit=None, **kwargs),看见有人写find_all(True),不知何意。
试了下:
def find_all(self, name=None, attrs={}, recursive=True, string=None, limit=None, **kwargs):print(f'name={name}, attrs={attrs}') find_all(1, True)name=True, attrs={}
'' == True是False. '' == False也是False
自定义类重载了__eq__时,使用==判断None会出错。{} '' 0都是False.