Python/Python Challenge

[Python Challenge 4] 무한으로 즐겨요 requests

Python Challenge 4의 url은 다음과 같다.

Python challenge 4 : http://www.pythonchallenge.com/pc/def/linkedlist.php

 

follow the chain

 

www.pythonchallenge.com


구성

으흠; 그림이 어떤 걸 의미하는지는 모르겠다. 관습적으로 소스 페이지를 확인해보자

그림에 a태그 href로 nothing=12345가 걸려있다. 눌러보자

오호 어떤 건지 알겠다. 재귀적으로 탐색하며 다음 nothing을 전달하다 보면 해결각이 나오나 보다 코딩 타임이다.


해결 아이디어

주석에는 urllib를 쓰라고 되어있는데 외부 모듈인 requests에 익숙해져 있는 필자는 이걸 쓰겠다. 문자열 탐색은 본문 페이지의 있는 nothing is가 고정임을 이용해서 저번 시간 사용한 정규표현식 re를 써본다.

import re
from requests import *

if __name__=="__main__" :
  url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="
  nothing = "12345"

  while(True) :
    new_url = url+nothing
    res = get(new_url)
    print(res.text)
    nothing = re.findall("nothing is (\d+)",res.text, re.DOTALL)[-1]

그릏다. re.findall 모듈은 정규표현식이 ()로 둘러싸인 곳만 list화 한다. 하다 보면 오류가 난다

...
and the next nothing is 54249
and the next nothing is 29247
and the next nothing is 13115
and the next nothing is 23053
and the next nothing is 3875
and the next nothing is 16044
Yes. Divide by two and keep going.
Traceback (most recent call last):
  File "\python_challenge\4.py", line 13, in <module>
    nothing = re.findall("nothing is (\d+)",res.text, re.DOTALL)[-1]
IndexError: list index out of range

반으로 나누란다. 8022를 집어넣고 계속해보자 중간에 무슨 잘못된 안내가 있다고 하는데, 우리가 짠 코드로는 그냥 넘어갈 수 있으니, 그냥 넘어가고 계속하다 보면 다음과 같은 결과가 나온다.

...
and the next nothing is 96791
and the next nothing is 75635
and the next nothing is 52899
and the next nothing is 66831
peak.html
Traceback (most recent call last):
  File "\python_challenge\4.py", line 13, in <module>
    nothing = re.findall("nothing is (\d+)",res.text, re.DOTALL)[-1]
IndexError: list index out of range

찾았다.

Answer Url : http://www.pythonchallenge.com/pc/def/peak.html