Python 请求库工作,urllib.request.urlopen POST 不工作

Python requests lib working, urllib.request.urlopen POST not working

requests.post 给了我正确的输出,请帮助我在 urllib 上获得相同的输出,目前,这是一个错误的请求 HTTP 400 错误。


Below is the data which is a dict object containing the url query:


data={'symbols': {'tickers': ['BITTREX:BTCUSDT'], 'query': {'types': []}}, 'columns': ['Recommend.Other|1W', 'Recommend.All|1W', 'Recommend.MA|1W', 'RSI|1W', 'RSI[1]|1W', 'Stoch.K|1W', 'Stoch.D|1W', 'Stoch.K[1]|1W', 'Stoch.D[1]|1W', 'CCI20|1W', 'CCI20[1]|1W', 'ADX|1W', 'ADX+DI|1W', 'ADX-DI|1W', 'ADX+DI[1]|1W', 'ADX-DI[1]|1W', 'AO|1W', 'AO[1]|1W', 'Mom|1W', 'Mom[1]|1W', 'MACD.macd|1W', 'MACD.signal|1W', 'Rec.Stoch.RSI|1W', 'Stoch.RSI.K|1W', 'Rec.WR|1W', 'W.R|1W', 'Rec.BBPower|1W', 'BBPower|1W', 'Rec.UO|1W', 'UO|1W', 'close|1W', 'EMA5|1W', 'SMA5|1W', 'EMA10|1W', 'SMA10|1W', 'EMA20|1W', 'SMA20|1W', 'EMA30|1W', 'SMA30|1W', 'EMA50|1W', 'SMA50|1W', 'EMA100|1W', 'SMA100|1W', 'EMA200|1W', 'SMA200|1W', 'Rec.Ichimoku|1W', 'Ichimoku.BLine|1W', 'Rec.VWMA|1W', 'VWMA|1W', 'Rec.HullMA9|1W', 'HullMA9|1W', 'Pivot.M.Classic.S3|1W', 'Pivot.M.Classic.S2|1W', 'Pivot.M.Classic.S1|1W', 'Pivot.M.Classic.Middle|1W', 'Pivot.M.Classic.R1|1W', 'Pivot.M.Classic.R2|1W', 'Pivot.M.Classic.R3|1W', 'Pivot.M.Fibonacci.S3|1W', 'Pivot.M.Fibonacci.S2|1W', 'Pivot.M.Fibonacci.S1|1W', 'Pivot.M.Fibonacci.Middle|1W', 'Pivot.M.Fibonacci.R1|1W', 'Pivot.M.Fibonacci.R2|1W', 'Pivot.M.Fibonacci.R3|1W', 'Pivot.M.Camarilla.S3|1W', 'Pivot.M.Camarilla.S2|1W', 'Pivot.M.Camarilla.S1|1W', 'Pivot.M.Camarilla.Middle|1W', 'Pivot.M.Camarilla.R1|1W', 'Pivot.M.Camarilla.R2|1W', 'Pivot.M.Camarilla.R3|1W', 'Pivot.M.Woodie.S3|1W', 'Pivot.M.Woodie.S2|1W', 'Pivot.M.Woodie.S1|1W', 'Pivot.M.Woodie.Middle|1W', 'Pivot.M.Woodie.R1|1W', 'Pivot.M.Woodie.R2|1W', 'Pivot.M.Woodie.R3|1W', 'Pivot.M.Demark.S1|1W', 'Pivot.M.Demark.Middle|1W', 'Pivot.M.Demark.R1|1W']}

这个有效:

url= 'https://scanner.tradingview.com/crypto/scan'
response = requests.post(url, json=data).text

但我想要这个 urllib,它目前抛出一个错误: 我在 运行ning requests.post 方法

之后从 response.header 得到了这个 header
headers={'Server': 'tv', 'Date': strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()),\
'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', \
 'Access-Control-Allow-Headers': 'X-UserId,X-UserExchanges,X-CSRFToken', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\
 'Access-Control-Allow-Credentials': 'true', 'Content-Encoding': 'gzip'}

params = urllib.parse.urlencode(data).encode('utf-8')

req = urllib.request.Request(url,data=params, headers=headers)

f = urllib.request.urlopen(req).read()

我只想 运行 使用 urllib 而不是使用 Python 3 中的 requests 库。

给定 dataheadersurl 已在您的问题中定义,尝试:

import urllib
import json           

req = urllib.request.Request(url, headers=headers)
jdata = json.dumps(data).encode('utf-8')    
response = urllib.request.urlopen(req, jdata)

然后

resp = response.read().decode('utf-8')
json.loads(resp)