使用Python向站点发送post请求时出现错误403

2024-06-09 18:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我正在为一个网站编写一个简单的脚本,将产品添加到购物车中,然后签出。脚本运行得很好,我决定重写它,使代码更干净,但现在我在向我的购物车添加产品的post请求时遇到了一个问题,我以前没有遇到过这个问题,网站也没有任何更改。我想我的标题可能有问题,但我没有看到其他任何东西。这是我的密码

import requests, re

headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36',
    'origin': 'https://www.colorskates.com',
    'connection': 'keep-alive',
    'cache-control': 'max-age=0',
    'upgrade-insecure-requests': '1'
}

s = requests.Session()

product = input('What shoe would you like to run for: ')
size = input('What size would you like to run for: ')

sizes = {
    '35': 37,
    '36': 7,
    '36.5': 24,
    '37': 8,
    '37.5': 9,
    '38': 10,
    '38.5': 22,
    '39': 11,
    '40': 12,
    '40 2/3': 187,
    '40.5': 84,
    '41': 13,
    '41 1/3': 188,
    '42': 14,
    '42 2/3': 189,
    '42.5': 15,
    '43': 16,
    '43 1/3': 190,
    '44': 17,
    '44 2/3': 191,
    '44.5': 21,
    '45': 18,
    '45 1/3': 192,
    '45.5': 39,
    '46': 19,
    '46.5': 147,
    '47': 47,
    '47.5': 117,
    '48': 48,
    '48.5': 85,
    '49.5': 177
}

product_atc = product  + '?action=add_product'
product_ids = int(re.search(r'\d+', product).group(0))

atc = s.post(product_atc, data={'id[2]': sizes[size], 'quantity': 1, 'products_id': product_ids}, headers=headers)

if atc.status_code not in (302, 200):
    print('Error adding item to cart ' + str(atc.status_code) + '..')
else:
    print('ATC Successful..')

403 error

Headers and form data

第二个图像是post请求中必须包含的标题和表单数据,我非常确定我正确地传递了它们


Tags: tore脚本标题sizeapplication产品网站
2条回答

看起来您收到了一个403 Forbidden错误。这意味着您无权访问所请求的资源

The HTTP 403 Forbidden client error status response code indicates that the server understood the request but refuses to authorize it

要修复它,您必须引用并使用您请求的API使用的授权方案

我发现了我的错误,我没有正确的标题,我只是修复了它们

headers = {
    'authority': 'www.colorskates.com',
    'path': product_atc[27:len(product_atc)],
    'cache-control': 'max-age=0',
    'referer': product,
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
}

相关问题 更多 >