的要實踐蟒蛇的一些位,我一直具有上pythonchallenge.com添加字符串結束URL
簡單的挑戰去,這個挑戰作爲第一步,需要一個加載一個HTML頁面從一個帶有數字的網址結束。該頁面包含一行文字,其中包含一個數字。該號碼用於替換網址中的現有號碼,因此會帶您進入序列中的下一頁。顯然這持續了一段時間......(這個挑戰還有更多,但讓這部分工作是第一步)。
我的代碼如下(僅限於序列中前四頁應該運行的代碼)。出於某種原因,它第一次工作 - 它獲得序列中的第二頁,讀取數字,進入第三頁,並在那裏讀取數字。但之後它就陷入了第三次。我不明白爲什麼,儘管認爲這可能與我將數字轉換爲字符串之前將其放在URL末尾的嘗試有關。要回答一個顯而易見的問題,是的,我知道,pythonchallenge正在確定 - 你可以手動執行URL號碼的事情,只要你有耐心,確認,如果你喜歡:P
import httplib2
import re
counter = 0
new = '12345' #the number for the initial page in the sequence, as a string
while True:
counter = counter + 1
if counter == 5:
break
original = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
nextpage = original+new #each page in the sequence is visited by adding
#the number after 'nothing='
print(nextpage)
h = httplib2.Http('.cache')
response, content = h.request(nextpage, "GET") #get the content of the page,
#which includes the number for the
#*next* page in the sequence
p = re.compile(r'\d{4,5}$') #regex to find a 4 to 5 digit number at the end of
#the content
new = str((p.findall(content))) #make the regex result a string - is this
#where the problem lies?
print('cached?', response.fromcache) #I was worried my requests were somehow
#being cached not actually sent afresh to
#pythonchallenge. But it seems they aren't.
print(content)
print(new)
而以上的輸出如下。對於第一次運行來說,它似乎工作正常(將92512添加到url併成功獲取下一頁並找到下一個值),但在此之後,它只是卡住了,似乎無法加載序列中的下一頁。通過在瀏覽器中手動更改網址來進行測試,確認該數字是正確的,並且pythonchallenge工作正常。
它看起來像我錯了將我的正則表達式搜索轉換爲一個字符串添加到URL的末尾 - 但爲什麼它應該第一次工作,而不是第二次我不知道。我也擔心,也許我的請求只能達到緩存(我是httplib2的新手,對它如何緩存沒有信心),但似乎沒有。我也在請求中添加了一個無緩存參數(僅在此代碼中顯示),但它沒有幫助。
http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345
( '緩存?',FALSE)
,下什麼是92512
[ '92512']
http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=[ '92512']
('cached?',False)
,下什麼是72758
[ '72758']
http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=[ '72758']
( '緩存?',FALSE)
,並在未來沒有什麼是72758
['72758']
http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=['72758']
('cached?」,FALSE)
,下什麼是72758
[ '72758']
我將不勝感激的人誰可以指出哪裏我錯了,以及對於任何相關的提示
在此先感謝...
當然啊,謝謝。我忘了所有關於使用搜索和組()來處理這個問題。 – Tom 2010-04-30 18:02:30