的要实践蟒蛇的一些位,我一直具有上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