'Add an item to cart with Python requests
I'm trying to add an item to the cart. I am fairly new to coding in python so I have tried to make some kind of code that will do it for me. But the code is not adding the item to the cart, and there is no errors when starting the code. So I want to hear if someone out there could help me fix this problem?
The item im trying to add in to the cart: here
My code:
from urllib import response
import requests, re, json
session = requests.session()
ProductSize = 44
def get_color_results(link):
headers = {"User-Agent": "Mozilla/5.0"}
r = requests.get(link, headers=headers).text
data = json.loads(re.search(r'(\{"enrichedEntity".*size.*)<\/script', r).group(1))
results = []
color = ""
for i in data["graphqlCache"]:
if "ern:product" in i:
if "product" in data["graphqlCache"][i]["data"]:
if "name" in data["graphqlCache"][i]["data"]["product"]:
results.append(data["graphqlCache"][i]["data"]["product"])
if (
color == ""
and "color" in data["graphqlCache"][i]["data"]["product"]
):
color = data["graphqlCache"][i]["data"]["product"]["color"]["name"]
return (color, results)
link = "https://www.zalando.dk/nike-sportswear-air-max-90-sneakers-ni112o0bt-a11.html"
final = {}
color, results = get_color_results(link)
colors = {
j["node"]["color"]["name"]: j["node"]["uri"]
for j in [
a
for b in [
i["family"]["products"]["edges"]
for i in results
if "family" in i
if "products" in i["family"]
]
for a in b
]
}
final[color] = {
j["size"]: j["offer"]["stock"]["quantity"]
for j in [i for i in results if "simples" in i][0]["simples"]
}
for k, v in colors.items():
if k not in final:
color, results = get_color_results(v)
final[color] = {
j["size"]: j["offer"]["stock"]["quantity"]
for j in [i for i in results if "simples" in i][0]["simples"]
}
def cart():
global session
response = "https://www.zalando.dk/api/graphql/add-to-cart/"
payload = "https://www.zalando.dk/api/rr/e"
if '"cartActionProductSize":"%s"'%(ProductSize) in payload.text and '"addToCart":' in response.text:
session.post(payload)
print("Added to cart")
elif '"addToCart":null' in response.text:
cart()
print("Something went wrong")
UPDATE
Hey, I have updated the post because some coding errors and I have made it so that is easier to understand.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
