【问题标题】:Getting shopping cart items using post request python使用发布请求python获取购物车项目
【发布时间】:2018-07-30 19:37:34
【问题描述】:

过去几天我一直在浏览 stackoverflow,并查看了许多不同的视频和论坛,但由于某种原因我无法使其正常工作。我正在尝试在https://www.toytokyo.com/medicom-toy-kaws-together-black/ 上自动将商品添加到购物车,我什至得到了正确的 200 响应代码,但是当检查购物车时它说它是空的。

这是它需要的请求负载。

------WebKitFormBoundary2abcTSnRV9XhBx4h
Content-Disposition: form-data; name="action"

add
------WebKitFormBoundary2abcTSnRV9XhBx4h
Content-Disposition: form-data; name="product_id"

4806
------WebKitFormBoundary2abcTSnRV9XhBx4h
Content-Disposition: form-data; name="qty[]"

1
------WebKitFormBoundary2abcTSnRV9XhBx4h--

这就是我发送 POST 请求的方法。

payload = {'action': 'add', 'product_id': 4806, 'qty[]': 1}

get = requests.get("https://www.toytokyo.com/medicom-toy-kaws-together-black/")

post = requests.post("https://www.toytokyo.com/remote/v1/cart/add", data=payload)

print(post.status_code, post.content)

get = requests.get("https://www.toytokyo.com/cart.php")

print(get.status_code, get.text)

我不确定我是否做错了什么,但我能从我所知道的情况中得到正确的回应。

编辑:答案如下

对于以后可能偶然发现的任何人,我听取了下面评论的人的建议,并创建了一个名为 session 的变量并使用 session = requests.Session() 分配它,这允许您的程序在每个新请求中持续存在你发送。 session 变量也具有与请求本身相同的所有方法。所以我只是替换了所有使用请求并将其替换为会话。

【问题讨论】:

  • 您可能缺少会话 cookie,它将您的请求捆绑在一起。您的最后一个 GET 请求需要被识别为与将商品添加到购物车的 POST 请求属于同一会话。
  • 查看question and answer,了解如何创建会话并在请求中使用 cookie。
  • 哇,你们是救生员,我刚刚尝试过,它似乎有效。谢谢

标签: python python-requests


【解决方案1】:

您执行了正确的 POST/GET 调用,但是您需要考虑这样一个事实,即您还需要一些方法来跟踪您的“会话”。可能在真实页面上,cookie 用于跟踪您购物车的内容。因此,当您请求购物车内容时,您需要包含此 cookie。为此,请使用 requests session 将 cookie 添加到您的代码中:

s = requests.Session() # cookies are stored in the session

payload = {'action': 'add', 'product_id': 4806, 'qty[]': 1}

get = s.get("https://www.toytokyo.com/medicom-toy-kaws-together-black/")

post = s.post("https://www.toytokyo.com/remote/v1/cart/add", data=payload)

print(post.status_code, post.content)

get = s.get("https://www.toytokyo.com/cart.php")

print(get.status_code, get.text)

【讨论】:

  • 你是对的。我还有一个问题,我看到会话有两种不同的工作方式。有 request.Session() 和 request.sessions 。有什么区别?
  • @shayang 这是两种不同的类型,request.sessions 是一个模块,request.Session() 是一个 requests.sessions.Session 的实例:>>> requests.sessions <module 'requests.sessions' from '/usr/local/lib/python2.7/dist-packages/requests/sessions.pyc'> >>> requests.Session() <requests.sessions.Session object at 0x1395f50>
  • 什么时候使用标题?我见过有人用,有人不用。需要吗?
  • 它是可选的,它实际上取决于您与之交谈的服务器/api。一些 REST api 需要任何 json 数据以标头 'Content-type:application/json' 发布,否则数据将不会被处理。
猜你喜欢
  • 2021-12-17
  • 1970-01-01
  • 2020-02-28
  • 2017-04-27
  • 2021-03-06
  • 2020-06-22
  • 2013-01-11
  • 2018-06-06
  • 1970-01-01
相关资源
最近更新 更多