清风竹林

ぷ雪飘绛梅映残红
   ぷ花舞霜飞映苍松
     ----- Do more,suffer less

Python Challenge lv4: follow the chain

  题目链接: http://www.pythonchallenge.com/pc/def/linkedlist.php
   
  说实话,好不容易通过google搞清楚题目的要求: 通过不断的从服务器取得一个web page,然后从源码中找出下一个链接的地址。需要注意的是:虽然页面的源码很简单,但并不是其中所有的数字都是有效的,需要使用正则表达式找出正确的pattern形式才可以,对本题而言r'nothing is (\d+)'是一个可用的pattern,使用''.join([x for x in text if x.isdigit()] 将所有的数字都粘连起来了,结果跟踪到4000多还没结束,才知道上当了。。。
 
import re
import urllib.request


if __name__ == '__main__':
    url 
= 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
    index 
= '17675'
    counter 
= 1
    pattern 
= re.compile(r'nothing is (\d+)')
    
while True:
        
try:
            request
= urllib.request.Request(url+index)
            
# my pc must use proxy to connect
            request.set_proxy('172.16.0.252:80''http')
            response
= urllib.request.urlopen(request) 
            content
=str(response.read().decode())
            response.close()    
            
print(counter, content)
            
            result 
= pattern.search(content)
            
if not result:
                
break
            
            index 
= result.group(1)
            counter 
+= 1        
        
except Exception as ex:
            
print(ex)
            
break
  程序输出:
1 and the next nothing is 8511
2 and the next nothing is 89456
3 and the next nothing is 43502
4 and the next nothing is 45605
5 and the next nothing is 12970
6 and the next nothing is 91060
7 and the next nothing is 27719
8 and the next nothing is 65667
9 peak.html

得到下一个题目的地址peak.html (注:我的index初始值是17675,题目中最早给出的可不是这个值, 我是从地址列表的后一部分选了一个数字而已,因此不要担心)

posted on 2009-05-11 16:05 李现民 阅读(548) 评论(2)  编辑 收藏 引用 所属分类: python

评论

# re: Python Challenge lv4: follow the chain[未登录] 2011-05-31 20:17 simon

有个问题想问:
你是如何知道要用nothing去做pattern的呢?  回复  更多评论   

# re: Python Challenge lv4: follow the chain 2011-06-01 10:04 李现民

@simon
你去看一个网页的源代码,里面有一个链接, 你点一下会出现 and the next nothing is 92512, 替换Url里linkedlist.php?nothing=12345中的12345,然后再回车, 你就会发现规律了  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理