Cookies 如何使用urllib2在Python中单独发送cookie

Cookies 如何使用urllib2在Python中单独发送cookie,cookies,urllib2,Cookies,Urllib2,我正在尝试向一个url发送多个cookie,直到找到正确的cookie为止,我不知道为什么我当前的代码不起作用 我已经查看了将cookies发送到url的现有答案,但在我的情况下,它们似乎都不起作用 代码中的注释是任务的说明 # Write a script that can guess cookie values # and send them to the url http://127.0.0.1:8082/cookiestore # Read the respons

我正在尝试向一个url发送多个cookie,直到找到正确的cookie为止,我不知道为什么我当前的代码不起作用

我已经查看了将cookies发送到url的现有答案,但在我的情况下,它们似乎都不起作用 代码中的注释是任务的说明

    # Write a script that can guess cookie values
    # and send them to the url http://127.0.0.1:8082/cookiestore
    # Read the response from the right cookie value to get the flag.
    # The cookie id the aliens are using is alien_id
    # the id is a number between 1 and 75 


    import urllib2

    req = urllib2.Request('http://127.0.0.1:8082/cookiestore')
    for i in range(75):
      req.add_header('alien_id', i)
      response = urllib2.urlopen(req)
      html = response.read()  
      print(html)

我原以为其中一次迭代会打印出一些不同的内容,但它们都是一样的

ahahaha cyber discovery,我明白了;) 你非常接近,事实上我使用你的代码作为我的基础,除了添加标题行。 不知道你是否还需要知道,但我会把这个留给其他人

当您将cookie作为标头发送时,您可以这样发送:

req.add_头('Cookie','cookiename=cookievalue')

希望这有帮助:D

这段代码是Python3.8,因为Python2.7不再受支持,您的
req.add_header
行确实需要修改。以下是您的解决方案:

import urllib.request

url = "http://127.0.0.1:8082/cookiestore"
y = 5

for i in range(75):
 request = urllib.request.Request(url)
 request.add_header("Cookie", "alien_id = "+str(i))
 response = urllib.request.urlopen(request)
 responseStr = str(response.read().decode("utf-8"))
 print(responseStr)
如果您仍在使用Python2.7,只需复制
请求.add_header
行即可。
干杯

你找到解决办法了吗?@Miffy,在下面;)或者至少对我有用。