如何生成随机的html文档

kar*_*mba 8 html python random grammar

我想生成完全随机的html源代码,可能来自语法.我想在python中这样做,但我不知道如何继续 - 是否有一个带语法的库,只是随机遵循其规则,打印路径?

想法?

mik*_*obi 7

import urllib

html = urllib.urlopen('http://random.yahoo.com/bin/ryl').read()
Run Code Online (Sandbox Code Playgroud)

我认为拉随机页面更容易实现,并且比你自己编程的任何东西都更随机.任何旨在生成随机页面的程序仍然必须遵守定义html结构的任何规则.由于人类比机器更好,破坏规则,因此来自网络的随机页面更可能包含您无法从随机化器获得的结构.

您不必使用雅虎,可能还有其他随机链接生成器,或者您可以构建自己的.

  • 不幸的是,雅虎页面不再存在.:-( (4认同)

小智 3

构建自己的随机 html 生成器非常容易,它看起来非常像自上而下的解析器。这里有一个基地!

def RandomHtml():
    yield '<html><body>'
    yield '<body>'
    yield RandomBody()
    yield '</body></html>'

def RandomBody():
    yield RandomSection()
    if random.randrange(2) == 0:
        yield RandomBody()

def RandomSection():
    yield '<h1>'
    yield RandomSentence()
    yield '</h1>'
    sentences = random.randrange(5, 20)
    for _ in xrange(sentences):
         yield RandomSentence()

def RandomSentence():
    words = random.randrange(5, 15)
    yield (' '.join(RandomWord() for _ in xrange(words)) + '.').capitalize()

def RandomWord():
    chars = random.randrange(2, 10)
    return ''.join(random.choice(string.ascii_lowercase) for _ in xrange(chars))

def Output(generator):
    if isinstance(generator, str):
        print generator
    else:
        for g in generator: Output(g)

Output(RandomHtml())
Run Code Online (Sandbox Code Playgroud)