【发布时间】:2020-04-24 18:40:15
【问题描述】:
我正在制作一个与 Steam 市场交互的 Python 机器人 (http://steamcommunity.com/market)。一切顺利,但是我坚持创建购买订单。我的 Python(3) 代码基于以下 javascript:
$J.ajax( {
url: 'https://steamcommunity.com/market/createbuyorder/',
type: 'POST',
data: {
sessionid: g_sessionID,
currency: g_rgWalletInfo['wallet_currency'],
appid: this.m_unAppId, // ITEM?
market_hash_name: this.m_strMarketHashName,
price_total: price_total,
quantity: quantity
},
crossDomain: true,
xhrFields: { withCredentials: true }
} ).done( function ( data ) {
CreateBuyOrderDialog.OnCreateBuyOrderComplete( { responseJSON: data } );
} ).fail( function( jqxhr ) {
// jquery doesn't parse json on fail
var data = $J.parseJSON( jqxhr.responseText );
CreateBuyOrderDialog.OnCreateBuyOrderComplete( { responseJSON: data } );
} );
其中currency/appid/price_total/quantity 是整数,sessionid 和market_hash_name 是字符串。我已将此代码重构为 Python 3:
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
urllib.request.install_opener(opener)
#before the request is made, cookies are 'created' by doing other requests on the same website
def placeOrder():
url = 'http://steamcommunity.com/market/createbuyorder'
values = {'sessionid' : self.sessionid,
'currency' : '3',
'appid' : '730',
'market_hash_name' : 'Chroma 2 Case',
'price_total' : '4',
'quantity' : '1'}
headers = {'Accept' : '*/*',
'Content-type' : 'application/x-www-form-urlencoded; charset=UTF-8',
'Referer' : 'http://steamcommunity.com/market/listings/730/Chroma%202%20Case',
'Accept-Language' : 'nl-NL',
'Origin' : 'http://steamcommunity.com',
'Accept-Encoding' : 'gzip, deflate',
'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Host' : 'steamcommunity.com',
'Connection' : 'Keep-Alive',
'Cache-Control' : 'no-cache'}
post = urllib.parse.urlencode(values)
binary_data = post.encode('utf-8')
request = urllib.request.Request(url, binary_data, headers)
response = urllib.request.urlopen(request)
data = json.loads(response.decode('utf-8'))
但是在调用placeOrder() 函数时会返回此错误:urllib.error.HTTPError: HTTP Error 400: Bad Request。
为什么这会产生错误的请求?因为我通过购买商品在此 url http://steamcommunity.com/market/listings/730/Chroma%202%20Case# 上创建了一个“真实”请求,从而准确地复制了标头和 cookie。
为什么网站会返回错误的请求?最有可能的是什么? (例如,缺少 cookie、缺少标头、缺少步骤等)
感谢您的帮助!
【问题讨论】:
-
我也遇到了同样的问题。通过在浏览器上创建一个真实的请求,我已经准确地复制了标题和 cookie。你是怎么解决这个错误的
标签: javascript python http cookies request