您的位置:首页 > 理论基础 > 计算机网络

python challenge 第四关解法 http://www.pythonchallenge.com

2011-10-12 00:33 543 查看
import re, urllib

nothing = '12345'
nothing = 16044 >> 1

# '82683', '82682'
nothing = str(nothing)
nothing = '63579'
re_match = re.compile(r'[^\d]*(\d+)').match

v = []

for i in xrange(500):
try:
print i
f = urllib.urlopen('http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='+nothing)
s = f.read()
f.close()
nothing = re_match(s).groups()[0]
v.append(nothing)
except:
break

f = open('challenge4-nothings', 'w')
f.write('\n'.join(v))
f.close()

print v[-1]


以上是我用来解决第四关的代码,第四关比较调皮,你一步走不到头,当然,我指的是第一次解决这个问题的时候,当你解决了这个问题后,你可以试着用更加聪明和简单的方法来解决这一关。

简单讲下我的思路:

进入第四关的网页 http://www.pythonchallenge.com/pc/def/linkedlist.php,如果我们在网页上无法查看到任何的提示信息,我们当然先得查看该网页的源码咯,它的源码如下:

<html>
<head>
<title>follow the chain</title>
<link rel="stylesheet" type="text/css" href="../style.css">
</head>
<body>
<!-- urllib may help. DON'T TRY ALL NOTHINGS, since it will never
end. 400 times is more than enough. -->
<center>
<a href="linkedlist.php?nothing=12345"><img src="chainsaw.jpg" border="0"/></a>
<br><br><font color="gold"></center>
Solutions to previous levels: <a href="http://wiki.pythonchallenge.com/"/>Python Challenge wiki</a>.
<br><br>
IRC: irc.freenode.net #pythonchallenge
</body>
</html>


我们看到了这句话:

<a href="linkedlist.php?nothing=12345"><img src="chainsaw.jpg" border="0"/></a>这说明,这个图片有个链接,我们点进去看看呗:
进去网页后,只有一句话:and the next nothing is 44827

自此就很明显了,我们需要用 这句话中的数字来替换刚刚图片中链接里的 12345,也就是,新的链接会是linkedlist.php?nothing=44827
这个时候,我们需要重点关注这句话:
<!-- urllib may help. DON'T TRY ALL NOTHINGS, since it will never
end. 400 times is more than enough. -->

很明显,它已经告诉了我们入手点是什么,当然是 urllib,不过要是你和我一样手贱的话,你也可以像我一样人工替换,我发誓,你会吐血的-_-

那么接下来就简单了,写个urllib的脚本,用正则获取下数字是多少(我正则很烂的,从脚本上就能看出来),第一次我们设置 nothing = 12345

运行结束后,输出了最后的那个数字:16044,手工输入链接linkedlist.php?nothing=16044
这个时候,页面提示我们要把 16044 除二,好吧,那我们除就是了,把得到的值再次赋值给nothing,好了,又一次运行脚本吧!!!


这一次,在 82683 处脚本结束了,我们手动输入 nothing = 82683的链接,页面提示我们跑多了,要往回退一页,好吧,到我们保存输入的文件中找到 82683 的上一个 nothing 值,原来是 82682,好吧

这次页面提示我们可以用的nothing为 63579, 再次赋值给nothing=63579,运行脚本:

脚本结束得到了一个值: 66831

手动输入地址栏试试,-_- ,结果是 peak.html

好吧,我们的第5关页面出现了: http://www.pythonchallenge.com/pc/def/peak.html

嘿嘿,总算是结束了,有点马拉松的感觉。

午夜 00:35 记录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐