问题
I am trying to make a bot in Python that can add a product to my cart on Supreme upon detection. I want this to be efficient, and when I try to use HTTP post requests to get the job done, I receive response code 200 (OK) but the product isn't added in my basket.
I have tried this with both the Python requests module and the selenium requests module. The code is below:
post_headers = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36', 'x-requested-with': 'XMLHttpRequest', 'content-type': 'application/x-www-form-urlencoded'}
post_data = {"utf-8": "%E2%9C%93", 's': size_id, 'st': style_id, "X-CSRF-Token": csrf, "commit": "add to cart"}
url = "https://www.supremenewyork.com/shop/{productid}/add".format(productid=id)
add_to_cart = session.post(url, headers=post_headers, data=post_data)
The response for add_to_cart
is the HTTP code 200 (OK) but when I run print(add_to_cart.text)
, I expect to see the product I added, however I just see []
(mobile user agent) or the supreme homepage html (desktop user agent), and figure out that there is nothing in the basket. I have also tried using a mobile user agent to get it working (json), and have also failed.
When I try to use selenium requests, I am using Google Chrome (otherwise I am using custom user agents).
I would appreciate any suggestion or way to fix this and be able to add products to my basket via HTTP POST requests.
回答1:
In order to see what you get in the response, you can also use .content
:
add_to_cart = session.post(url, headers=post_headers, data=post_data)
print(add_to_cart.content)
From what I see being returned in that content, only var h = {"76049":1,"cookie":"1 item--76049,26482"}
can be helpful to verify it was added.
Per what I see on that site, in order to get the full contents of the cart, you should also do another API call, GET on https://www.supremenewyork.com/shop/cart
with your headers.
Hopefully, this is helpful. Good luck!
回答2:
Why are you expecting to see your cart in the response to that POST? I know it seems logical that it perhaps would, but many websites are built in strange and mysterious ways.
Are you using the Chrome Developer Tools? If you look in the Network tab for a request to add something to the cart, you'll see under the response tab you just get a load of JavaScript back. However, if you look under the response cookies, you'll see something like this:
cart 1+item--62197%2C28449
Which looks like the product IDs for whats in the cart, is in a Cookie. You could then look for that in your response by calling:
add_to_cart.cookies["cart"]
Alternatively, you could do a GET on:
https://www.supremenewyork.com/shop/cart
but you would then need to parse the HTML you get back.. probably easier to check the Cookies.
来源:https://stackoverflow.com/questions/60695930/adding-a-product-to-cart-on-supreme-via-post-requests-in-python-request-not-wo