【问题标题】:How to enable cookie with Python requests?如何使用 Python 请求启用 cookie?
【发布时间】:2018-04-16 22:54:58
【问题描述】:

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

您能告诉我如何修复代码吗?为什么“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)

【问题讨论】:

  • 为什么需要获取登录网址?如果您检查 amazon.com 中的登录表单,您会发现该表单具有操作和方法。并且,使用输入数据提交表单。
  • 登录网址和操作值几乎相同。如果我运行“session.post(action_url, signin_data)”,结果 html 会显示“请启用 Cookie”

标签: python cookies web-scraping


【解决方案1】:

您对requests.Session() 的使用是正确的,所以我认为问题不在于cookie,而在于您的登录。亚马逊和 Facebook 等网站有时需要表单元数据以及您当前未通过的登录 Web 请求。如果我是对的,this answer 应该可以帮到你。

【讨论】:

    【解决方案2】:

    终于找不到答案了... 相反,我使用“Selenium”,我可以很容易地做到这一点。

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

    【讨论】:

      【解决方案3】:
      res = s.get('https://mysite[dot]com')
      cookies = dict(res.cookies)
      res = s.post('https://login[dot]mysite[dot]com', auth=('Email', 'Password'), verify=False, 
      cookies=cookies)
      

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

      【讨论】:

      • 这不是他要求的。
      • cookies 包含“{}”(无)
      猜你喜欢
      • 1970-01-01
      • 2021-12-02
      • 2015-10-11
      • 2014-05-26
      • 2019-09-07
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多