import urllib
html = urllib.urlopen('http://random.yahoo.com/bin/ryl').read()
Run Code Online (Sandbox Code Playgroud)
我认为拉随机页面更容易实现,并且比你自己编程的任何东西都更随机.任何旨在生成随机页面的程序仍然必须遵守定义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())
Run Code Online (Sandbox Code Playgroud)