Trying to set cookies but get a TypeError: string indices must be integers, not str

Trying to set cookies but get a TypeError: string indices must be integers, not str

我有 python 代码如下所示

from shlex import split
import requests
from bs4 import BeautifulSoup
import re
import mechanize
import urllib
with open("Myaccount.txt") as f:
    for line in f:
        parts = line.split(':')
        print parts[0]
        br = mechanize.Browser()
        br.set_handle_robots(False)
        br.addheaders = [("User-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36")]
        sign_in = br.open("https://website.com/login/")
        br.select_form(nr = 0)
        br["username"] = parts[0] 
        br["password"] = parts[1]   
        logged_in = br.submit()   
        logincheck = logged_in.read()
        print "logincheck"
        cookies = br._ua_handlers['_cookies'].cookiejar
        payload = {'action':'info',
                   'action':'info',
                   'api_key':'something'
                   }

        with open("cookie.txt", "w") as text_file:
            text_file.write("%s" % cookies)
            payload = {'action':'info',
                   'action':'info',
                   'api_key':'something'
                   }
            text_file.close()

        with open("cookie.txt", "r") as text_file:
            for line in text_file:
                yup = line
                payload = {'action':'info',
                   'action':'info',
                   'api_key':'something'
                   }
                print yup
                r = requests.post("https://website.com",data = payload, cookies =yup)

但是无论我做什么,我都会不断收到错误 "TypeError: string indices must be integers, not str",只有当完全从我底部的 post 请求中删除 "cookie" 时,它似乎才会消失,任何帮助将不胜感激

这是回溯错误的样子

Traceback (most recent call last):
  File "C:/Users/my name/Desktop/program.py", line 43, in <module>
    r = requests.post("https://website.com",data = payload, cookies = cookies)
  File "C:\Python27\lib\requests\api.py", line 108, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Python27\lib\requests\api.py", line 50, in request
    response = session.request(method=method, url=url, **kwargs)
  File "C:\Python27\lib\requests\sessions.py", line 450, in request
    prep = self.prepare_request(req)
  File "C:\Python27\lib\requests\sessions.py", line 358, in prepare_request
    cookies = cookiejar_from_dict(cookies)
  File "C:\Python27\lib\requests\cookies.py", line 439, in cookiejar_from_dict
    cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
TypeError: string indices must be integers, not str

在请求中,当你在请求中尝试 to send cookies 时,cookies kwarg 应该是一个字典。相反,您尝试发送的是一个字符串。将其更改为您尝试作为 cookie 发送的内容的字典。

编辑:我看到您正在尝试将 cookie 保存到文件中,然后将其用于以后的请求。这里发生的事情是您按原样保存 cookiejar 对象。当您尝试检索它时,这无济于事。相反,您应该做的是腌制对象并保存它。 Python请求框架提供了一种将cookiejar对象转换为字典的方法requests.utils.dict_from_cookiejar

cookies = br._ua_handlers['_cookies'].cookiejar
payload = {'action':'info',
               'action':'info',
               'api_key':'something'
               }

with open("cookie.txt", "w") as text_file:
    text_file.write("%s" % cookies)
    payload = {'action':'info',
               'action':'info',
               'api_key':'something'
               }
    text_file.close()

应该改为

import requests, pickle
with open('cookie.txt', 'w') as text_file:
    pickle.dump(requests.utils.dict_from_cookiejar(br._ua_handlers['_cookies'].cookiejar), text_file)

然后当你获取 cookie 时,它​​应该是

with open('cookie.txt', 'r') as text_file:
    yup = requests.utils.cookiejar_from_dict(pickle.load(text_file))