如何生成随机HTML文档
我想生成一段完全随机的HTML代码,可能是根据某种语法规则来生成的。我想用Python来实现这个,但我不知道该怎么开始——有没有什么库可以根据语法规则随机生成代码,并把生成的过程打印出来呢?
有什么想法吗?
2 个回答
7
import urllib
html = urllib.urlopen('http://random.yahoo.com/bin/ryl').read()
我觉得随机获取一个网页要简单得多,而且比你自己编程生成的随机页面要随机得多。任何设计用来生成随机网页的程序都必须遵循HTML的结构规则。因为人类在打破规则方面比机器要强得多,所以从网上随机获取的页面更可能包含一些你用随机生成器得不到的结构。
你不一定要使用雅虎,可能还有其他的随机链接生成器,或者你可以自己制作一个。
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())