首页 > 解决方案 > Python 请求返回 200 状态码但没有做我想做的事

问题描述

我对 Python 很陌生,但我正在尝试为一个名为 Zalando 的欧洲网站制作自己的运动鞋机器人。

我正在使用请求来自动化将商品添加到购物车的过程,但它并没有按照我想要的方式工作。当我打印状态代码时,它返回 200 但不会将商品添加到我的购物车中,这是我想要实现的。

部分代码:

session = requests.Session()

def create_atc_payload():

    payload =   {
            '0': {"id":"e7f9dfd05f6b992d05ec8d79803ce6a6bcfb0a10972d4d9731c6b94f6ec75033","variables":{"addToCartInput":{"productId":"NI115O002-Q120115000","clientMutationId":"addToCartMutation"}}}
    }

    return payload


def login():
    global session

    with open('zalando.csv', mode = 'r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        line_count = 0
        firstline = True
        for row in csv_reader:
            if firstline:
                firstline = False
                continue

            headers = {
                'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36' ,
                'Cookie' : 'cookie'
                }
            
            endpoint = "https://www.zalando.ie/cart"

            p = session.post(endpoint, data=create_atc_payload(), headers=headers, timeout = 10)
            print(p.status_code)
            time.sleep(4)
            
            response = session.get(endpoint, headers=headers)

            soup = bs(response.text, "html.parser")

            classes = soup.find_all("div",{"class":"z-coast-base__article-in-cart"})

            cart = []

            for item in classes:
                item_id = item["id"]
                cart.append(item_id)

            line_count += 1
        
    print(cart)

login()

输出:

200
[]

当我手动将商品添加到我的购物车然后使用“获取”请求时,它会正确打印出来,如下所示:

200
['article-NI115O002-Q120115000']

我的朋友使用 JavaScript 编写了一个 chrome 扩展脚本并使用相同的方法,以及他的作品。在过去的 3 天里,我一直在努力寻找解决方案,并且一直为此失眠。任何帮助深表感谢!

标签: pythonpython-3.xpython-requests

解决方案


推荐阅读