使用python向网站发送发布请求时出现错误403

时间:2020-04-14 17:49:09

标签: python python-requests

因此,我正在为一个简单的脚本编写一个站点,该站点将产品添加到购物车,然后签出。该脚本运行良好,我决定重写它,以便使代码更简洁,但是现在在发出将产品添加到我的购物车中的发布请求时,我遇到了一个问题,而该问题我以前从未遇到过,并且该站点没有任何更改。我认为标题可能有问题,但是我什么都没看到。这是我的代码。

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

第二个图像是标题和表单数据,它们必须在邮寄请求中,我很确定我正确地传递了它们。

2 个答案:

答案 0 :(得分:1)

好像您收到403 Forbidden错误。这意味着您无权访问所请求的资源。

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

要修复此问题,您必须引用并使用所请求的API使用的授权方案。

答案 1 :(得分:0)

我发现了我的错误,我没有正确的标头,只是对其进行了修复。

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'
}