Python请求在将变量的结果添加为param时将ambersand(&)附加到URL

2024-10-03 17:17:17 发布

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

下面是我的代码,它基本上从数据库中检索数据,将其放入CSV格式的变量中,然后我尝试将其附加到GET请求URL中。但是,get请求会导致null,因为GET请求URL中有一个符号(&

问题是我如何摆脱它

这是URL,请注意符号(&):

https://demo-api.ig.com/gateway/deal/clientsentiment?marketIds=&JGB,BCHUSD,AT20,
import requests
import json
import time
import datetime
import csv
import pandas as pd
import psycopg2

conn_string = "host=' dbname='' user='' password=''"

conn = psycopg2.connect(conn_string)

cursor=conn.cursor()
# Query to source marketIds
postgreSQL_select_Query = "SELECT DISTINCT () FROM static WHERE TYPE!='' AND marketId!='None'"

cursor.execute(postgreSQL_select_Query)
#print("Selecting marketId from table using cursor.fetchall")
instrument_static_marketId = cursor.fetchall()

cursor.execute(postgreSQL_select_Query )

#This puts the sql result into nice CSV format
y=','.join([y[0] for y in cursor.fetchall() ])
print(y)

# closing database connection.
conn.close ()

def main():
    headers = {
        'Connection': 'keep-alive',
        'Origin': 'https://.com',
        'X-IG-API-KEY': '',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept': 'application/json; charset=UTF-8',
        'X-SECURITY-TOKEN': '',
        'CST': '',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-Mode': 'cors',
        'Referer': 'https://',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8',
    }

    response = requests.get('https://demo-api.ig.com/gateway/deal/clientsentiment?marketIds=',params=y, headers=headers)
    print(response.url)
    result = response.json()
    print(result)


if __name__ == '__main__':
    main()

Tags: httpsimportcomjsonurlpostgresqlresultconn
1条回答
网友
1楼 · 发布于 2024-10-03 17:17:17

您在URL中包含了一个参数的一部分,该参数是不正确和混乱的请求

关闭该选项,然后为params传递一个字典,就像您已经在使用headers一样:

y = 'JGB,BCHUSD,AT20'

params = {
    'marketIDs': y,
}

url = 'https://demo-api.ig.com/gateway/deal/clientsentiment'

response = requests.get(url, params=params, headers=headers)

相关问题 更多 >