机器人框架传递cookie以获取请求(RequestsLibrary) - TypeError

时间:2017-04-21 13:09:16

标签: python cookies automated-tests python-requests robotframework

我需要将Cookie值传递给Get request关键字以使其正常工作,但它仍然失败。我不知道如何在那里正确传递它。关键字的文档说明了标题:"标题:与请求一起使用的标题字典" 我使用库RequestsLibrary

进行了这样的测试
Check request and response
    Do Local Login  ${username}    ${password}  #this is my custom keyword - opens browser and logs in using UI
    ${cookie_value}=  Get Cookie Value  JSESSIONID
    Create Session  session1  https://oururl.com  verify=${False}  cookies=${cookie_value}
    ${dict}=  Create Dictionary   Cookie=${cookie_value}
    ${resp}=  Get request  session1  /somepage/request  headers=${dict}

它始终返回TypeError: string indices must be integers。 回溯:

        Traceback (most recent call last):
  File "c:\python27\lib\site-packages\RequestsLibrary\RequestsKeywords.py", line 370, in get_request
    session, uri, params, headers, json, redir, timeout)
  File "c:\python27\lib\site-packages\RequestsLibrary\RequestsKeywords.py", line 897, in _get_request
    verify=self.verify)
  File "c:\python27\lib\site-packages\requests\sessions.py", line 501, in get
    return self.request('GET', url, **kwargs)
  File "c:\python27\lib\site-packages\requests\sessions.py", line 474, in request
    prep = self.prepare_request(req)
  File "c:\python27\lib\site-packages\requests\sessions.py", line 385, in prepare_request
    cookies = cookiejar_from_dict(cookies)
  File "c:\python27\lib\site-packages\requests\cookies.py", line 518, in cookiejar_from_dict
    cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))

我真的需要将cookie传递给请求,否则它只会再次返回登录页面。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

Sooo终于找到了解决方案:

    Do Local Login  ${username}    ${password}
    ${cookie_value}=  Get Cookie Value  JSESSIONID
    ${dict}=  Create Dictionary   JSESSIONID=${cookie_value}
    Create Session  session1  https://oururl.com  verify=${False}  cookies=${dict}
    ${resp}=  Get request  session1  /somepage/request

关键字Create Session适用于Cookie,只是cookie必须传递的不仅仅是Cookie值,还有字典JSESSIONID=${cookie_value}。 或者,我不必在Create Session中传递Cookie,但在Get Request中,我必须将Cookie设为字典${dict}= Create Dictionary Cookie=JSESSIONID=${cookie_value},然后传入Get request session1 /somepage/request headers=${dict} }