如何使用Python请求启用cookie?

如何使用Python请求启用cookie?,python,cookies,web-scraping,Python,Cookies,Web Scraping,我想用Python登录Amazon.com。 但即使我使用requests.Session(),我也不能这样做,因为我不能“启用Cookies” 你能告诉我怎么修改代码吗?为什么“dict(response.cookies)”返回空 # creating all input tag information (hidden tags are included) # {'pageId': 'ape:dXNmbGV....'email': 'xxx@xxx', 'password':

我想用Python登录Amazon.com。 但即使我使用requests.Session(),我也不能这样做,因为我不能“启用Cookies”

你能告诉我怎么修改代码吗?为什么“dict(response.cookies)”返回空

    # 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)
最后输出(html)------------------
请启用Cookie以继续 要继续在Amazon.com上购物,请在Web浏览器中启用Cookie。 在浏览器中启用Cookie后,请单击下面的按钮返回上一页

我想获得登录后的首页(你的Amazon.com)


您可以通过post()调用传递cookies。

您对
requests.Session()
的使用是正确的,因此我认为问题不在于cookies,而在于您的登录。像Amazon和Facebook这样的网站有时需要表单元数据以及您当前未传递的登录web请求。如果我是对的,我应该能够帮助你。

最后我找不到答案。。。 相反,我使用“硒”,我可以很容易地做到这一点

driver = Chrome(DRIVER_PATH)
driver.get(TOP_URL)
driver.find_element_by_id(SIGNIN_BUTTON).click()
driver.find_element_by_id(MAIL).send_keys(user_name)
elem_pass = driver.find_element_by_id(PASSWORD)
elem_pass.send_keys(user_password)
elem_pass.submit()

为什么需要获取登录url?如果您在amazon.com中检查登录表单,您会发现该表单具有操作和方法。并且,使用输入数据提交表单。登录url和操作值几乎相同。如果我运行“session.post(action\u url,signin\u data)”,结果html显示“请启用Cookies”,这不是他要求的。Cookies包含“{}”(无)
driver = Chrome(DRIVER_PATH)
driver.get(TOP_URL)
driver.find_element_by_id(SIGNIN_BUTTON).click()
driver.find_element_by_id(MAIL).send_keys(user_name)
elem_pass = driver.find_element_by_id(PASSWORD)
elem_pass.send_keys(user_password)
elem_pass.submit()