[Python] How to enable cookie with Python requests?

Discussão em 'Python' iniciado por Stack, Março 3, 2025.

  1. Stack

    Stack Membro Participativo

    I want to sign in Amazon.com with Python. But I can't do it even if I use requests.Session() , because I can't "Enable Cookies".

    Could you tell me how to fix the code? Why "dict(response.cookies)" return empty?

    # creating all input tag information (hidden tags are included)
    # {'pageId': 'ape:dXNmbGV....'email': 'xxx@xxx', 'password': 'xxx', 'create': '0'}
    def create_signin_data(res, user, pass) -> str:
    bs = BeautifulSoup(res.content, "html.parser")
    signin_data = {s["name"]: s["value"]
    for s in bs.select("form[name=signIn]")[0].select("input[name]")
    if s.has_attr("value")}
    signin_data[u"email"] = user
    signin_data[u"password"] = pass
    return signin_data

    signin_url ="https://www.amazon.com/ap/signin?_encoding=UTF8&........."
    action_url ="https://www.amazon.com/ap/signin"

    ### create session
    session = requests.Session()
    res = session.get(signin_url)
    # res = session.get(signin_url, cookies = res.cookies) -> the result is the same
    cookie_data = dict(response.cookies) # empty dict {}

    ### sign in
    signin_data = create_signin_data(res, "user@addr", "pass")
    res = session.post(signin_url, signin_data)
    # res = session.post(action_url, signin_data) -> the result is the same
    # res = session.post(signin_url, signin_data, cookies=cookie_data ) -> the result is the same

    print(res.content)


    the last out put (html) -----------------
    Please Enable Cookies to Continue To continue shopping at Amazon.com, please enable cookies in your Web browser. Once you have enabled cookies in your browser, please click on the button below to return to the previous page.

    I want to get post-login top page (your Amazon.com)

    Continue reading...

Compartilhe esta Página