Python Challenge lv4: follow the chain

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,题目中最早给出的可不是这个值, 我是从地址列表的后一部分选了一个数字而已,因此不要担心)

你可能感兴趣的:(Python Challenge lv4: follow the chain)