gpt4 book ai didi

python - 不断循环,无法弄清楚出了什么问题

转载 作者:行者123 更新时间:2023-12-04 16:20:44 25 4
gpt4 key购买 nike

我下面的代码没有按照我想要的方式工作,我试图对其进行一些评论以使其更容易。

基本上,我希望它最多尝试 3 次访问网站,如果成功,它将退出循环并继续,如果失败 3 次,它将退出该功能。

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

最佳答案

如果发生错误,continue被执行; while如果错误不断出现,则循环永远不会结束。

def test():
for i in range(0, 3):
while True:
try:
...
break
except:
continue # <---
break

恕我直言, while循环是不必要的:
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

关于python - 不断循环,无法弄清楚出了什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18407863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com