使用后期请求python获取购物车物品

时间:2018-07-30 19:37:34

标签: python python-requests

在过去的几天里,我一直在浏览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变量还具有与请求本身相同的所有方法。因此,我只是替换了所有使用请求的内容,并将其替换为会话。

1 个答案:

答案 0 :(得分:0)

您执行正确的POST / GET调用,但是您需要考虑以下事实:您还需要某种方式来跟踪“会话”。 Cookies可能在真实页面上用于跟踪购物车中的内容。因此,当您请求购物车中的物品时,您将需要包含此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)