Python 不断循环,无法计算出什么';出问题了
我下面的代码没有按我所希望的方式工作,我已经尝试对其进行一些注释以使其更容易 基本上,我希望它尝试最多三次访问网站,如果成功,它将退出循环并继续,如果失败三次,它将退出功能Python 不断循环,无法计算出什么';出问题了,python,python-2.7,random,proxy,mechanize,Python,Python 2.7,Random,Proxy,Mechanize,我下面的代码没有按我所希望的方式工作,我已经尝试对其进行一些注释以使其更容易 基本上,我希望它尝试最多三次访问网站,如果成功,它将退出循环并继续,如果失败三次,它将退出功能 import random import urllib2 import httplib import urllib import mechanize def test(): ## For three attempts... for i in range(0, 3): ## While in
import random
import urllib2
import httplib
import urllib
import mechanize
def test():
## For three attempts...
for i in range(0, 3):
## While in the three attempts...
while True:
## Try...
try:
print "trying"
## Proxy list
proxy_list = {"No Proxy": "None"}
## Randomly chosen proxy
proxy_number = random.choice(proxy_list.keys())
## URL to post to in order to get data.
post_url = ""
browser = mechanize.Browser()
browser.set_handle_robots(False)
browser.addheaders = [('User-agent', 'Firefox')]
parameters = {""}
data = urllib.urlencode(parameters)
## If proxy_number = No Proxy then...
if proxy_number == "No Proxy":
## Do not setup proxy details
proxy_details = None
## If proxy_number is a real proxy then...
else:
## Get the proxy details
proxy_details = proxy_list[proxy_number]
## Setup the proxy
browser.set_proxies({"http": proxy_number})
## Contact the webpage
trans_array = browser.open(post_url).read().decode('UTF-8')
print trans_array
## If successfully exit loop
break
## On exceptions
except:
## If unsuccessful continue and retry
continue
## End the current loop
break
## If it was unsuccessful after three attempts return false
return
print trans_array
test()
谁能解释我做错了什么
编辑:用于falsetru
def test():
for i in range(3):
try:
...
break
except:
counter = counter + 1
print counter
continue
if counter == 3:
return False
提前谢谢
-Hyflex如果发生错误,则执行
继续
<如果错误持续出现,则代码>while循环永远不会结束
def test():
for i in range(0, 3):
while True:
try:
...
break
except:
continue # <---
break
在我看来,因为你继续处理异常,如果每次都发生异常,while循环将无限执行你的while循环将始终为true,for循环将永远不会超过范围1Hey@falsetru,那么我如何才能使你的固定示例在第三次失败后退出函数?@Hyflex,使用范围(3)中的I的
:
,它的运行时间不超过三次。@FalseTreal,是的,我理解该部分,但我希望它能够在第三次失败后退出函数,但如果它没有失败,它将跳过下面的部分。看我的edit@Hyflex,下面是什么print trans_array
?@Hyflex,您可以将用于。。else..
语句。请参阅更新的代码。
def test():
for i in range(3):
try:
...
break
except:
continue
else:
return # Reach here if for loop was not ended by break
print trans_array