【问题标题】:Error 403 when sending a post request to a site with Python使用 Python 向站点发送发布请求时出现错误 403
【发布时间】:2020-04-14 17:49:09
【问题描述】:

所以我正在为一个将产品添加到购物车然后结帐的网站编写一个简单的脚本。该脚本运行良好,我决定重写它以使代码更简洁,但是现在我在发出将产品添加到我以前没有遇到的购物车的发布请求时遇到了一个问题,并且该网站没有更改任何内容.我认为我的标题可能有问题,但我没有看到其他任何内容。这是我的代码。

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..')

第二张图片是发布请求中必须包含的标题和表单数据,我很确定我正确地传递了它们。

【问题讨论】:

标签: python python-requests


【解决方案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 所使用的授权方案。

【讨论】:

  • 那么,如果我运行添加了代理的脚本,请求最有可能通过吗?因为现在我在本地运行我的脚本,我仍然可以访问该站点并将东西添加到我的购物车。
  • 它可能是作为标头传递的身份验证令牌。您如何使用 API 进行身份验证实际上仅取决于您使用的 API
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2015-04-23
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多