【问题标题】:How to send cookies separately in Python with urllib2如何使用 urllib2 在 Python 中单独发送 cookie
【发布时间】:2019-04-04 18:33:11
【问题描述】:

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

我查看了将 cookie 发送到 url 的现有答案,但它们似乎都不适用于我的情况 代码中的cmets是任务的指令

    # 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)

我预计其中一次迭代会打印出不同的东西,但它们都是一样的

【问题讨论】:

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

标签: cookies urllib2


【解决方案1】:

此代码是 Python 3.8,因为不再支持 Python 2.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)

如果您仍在使用 Python 2.7,则只需复制 request.add_header 行即可。 干杯!

【讨论】:

    【解决方案2】:

    啊哈哈网络发现我明白了;) 你非常接近,事实上我使用你的代码作为我的基础,除了添加标题行。 不知道你是否还需要知道,但我会把它留在这里给其他人

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

    req.add_header('Cookie', 'cookiename=cookievalue')
    

    希望这会有所帮助:D

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2013-05-12
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      相关资源
      最近更新 更多