python challenge 解題 第4關

範範不愛吃飯發表於2021-01-02

第四關

點選圖片,跳轉到頁面,顯示文字為“and the next nothing is xxx”,檢視原始碼提示,嘗試400次就足夠找到頁面。
本關是用文字中的數字替換url中的數字,找到真正的下一關連結。
運用爬蟲基礎。

import requests

# 初始化第一次的url
url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345"
r = requests.get(url)

# 迴圈四百次
for i in range(400):
    print(r.text)
    url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=" + r.text.split()[-1]
    r = requests.get(url)

檢視輸出,大多數輸出都是“and the next nothing is”, 某一次輸出是以“.html”結尾的,這行就是答案了,輸入到URL中。
中間有一些輸出很有意思,有的輸出中不帶數字,比如

Yes. Divide by two and keep going.

用我的程式碼, catch到的是最後一個單詞 going,如果把going輸入到URL中替換數字也可以繼續進行。或者像它提示的那樣,把url中的數字除以2,也可以繼續進行。
我又寫了段程式碼,讓它可以在提示的地方把數字除以2。但是結果也是一樣的,也沒有加快得到結果的速度。

for i in range(400):
    print(r.text, ' and catch: ', r.text.split()[-1])
    try:
        nr = int(r.text.split()[-1])
        url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=" + r.text.split()[-1]
        r = requests.get(url)
    except:
        # 如果最後一個單詞不是數字,就把url中的數字除以二。
        nr = nr / 2
        url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=" + str(nr)
        r = requests.get(url)

相關文章