python-对for循环的帮助
我是Python的完全初学者 为了一件事,我整天都在用头敲击键盘 我正在登录一个网站。如果您成功登录,您的用户名将出现在cookies中python-对for循环的帮助,python,loops,Python,Loops,我是Python的完全初学者 为了一件事,我整天都在用头敲击键盘 我正在登录一个网站。如果您成功登录,您的用户名将出现在cookies中 #other stuff cookies=requests.Session() def loggedIn() global cookie for cookie in cookies.cookies: cookie = cookie.value if username in cookie:
#other stuff
cookies=requests.Session()
def loggedIn()
global cookie
for cookie in cookies.cookies:
cookie = cookie.value
if username in cookie:
print 'yay'
if username not in cookie:
print 'goodbye cruel world'
loggedIn()
raw_input()
如果成功登录,cookie将有3个值
token
username
blabla
如果未成功登录,cookie将有2个值
token
blabla
因此,我使用正确的密码运行代码,得到的结果如下:
goodbye cruel world
yay
goodbye cruel world
使用错误的密码:
yay
goodbye cruel world
这就是我想要的:
如果用户名在cookie中,它将打印一次内容并结束循环
如果用户名在cookie中是而不是,它将打印一次内容并结束循环
我真的很困惑
for cookie in cookies.cookies:
cookie = cookie.value
检查代码。它正在修改作用域在for内的变量cookie
也许是这样
cookies = requests.Session()
def loggedIn():
for cookie in cookies.cookies:
if 'username' in cookie.value
return True
return False
if loggedIn():
print 'yay'
else:
print 'goodbye'
raw_input()
当您为循环调用
时,如果您更改它正在调用的变量,它将使用更改后的变量,如下所示:
>>> forever = ['a']
>>> for k in forever:
... print k
... forever.append(k)
...
a
a
a
a
a
...
这使其成为while
循环。如果要停止此操作,请事先将变量设置为其他值:
>>> forever = ['a']
>>> duplicate = forever
>>> for k in duplicate:
... print k
... forever.append(k)
...
a
>>>
因此,尝试更改for
循环,它将有望清理所有内容
if username in cookie:
print 'yay'
else:
print 'goodbye cruel world'
会更有意义。也可能是这个
for cookie in cookies.cookies:
if('user' in cookie):
print 'User Valid'
print 'User Invalid'
但是如果“username”不是用户名呢?我的印象是,token
,username
,blabla
是字段名。也许我错了,不是你:)OP也许能告诉我们;-)成功了。退货的目的是什么?此外,username是一个变量:)您的代码是否正常工作?变量username来自哪里?请提供有效的代码并反映您的问题是的,它有效,但不是我希望它如何工作。username来自sys.argv[1]在这种情况下,请提供处理sys.argv的代码,或生成“username='usr'”语句,以便代码可以在解释器中运行。它有助于解决您的问题。