1

我有python代码,它为我VWAP提供了衍生脚本的价值。

import requests
import json
from bs4 import BeautifulSoup as bs

r = requests.get('https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuoteFO.jsp?underlying=INFY&instrument=FUTSTK&expiry=30MAY2019&type=-&strike=-')
soup = bs(r.content, 'lxml')
data = json.loads(soup.select_one('#responseDiv').text.strip())
vwap = data['data'][0]['vwap']
print(vwap)

URL 有一种模式,其中只是底层名称的更改。例如在给定的 2 个 URL 中:

https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuoteFO.jsp?underlying=RELIANCE&instrument=FUTSTK&expiry=30MAY2019&type=-&strike=-

https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuoteFO.jsp?underlying=INFY&instrument=FUTSTK&expiry=30MAY2019&type=-&strike=-

当脚本名称和脚本名称在 URL 中更改时,程序要求输入的代码可能是什么?

4

1 回答 1

0

参数 torequests.get(...)是一个字符串,您可以像操作字符串一样操作它。对于这种情况,我建议使用str.format()(或者你也可以使用f-strings)。

base_url = 'https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuoteFO.jsp?underlying={}&instrument=FUTSTK&expiry=30MAY2019&type=-&strike=-'
underlying_list = ['RELIANCE', 'INFY']

for underlying in underlying_list:
    url = base_url.format(underlying)
    print(url)
    resp = requests.get(url)
    ...

如果 URL 的其他部分需要对每个调用有所不同,这种方法还允许您使用更多参数;您只需在.format()调用中添加更多参数(并相应地修改base_url以接受这些新参数)。

于 2019-05-16T18:12:41.637 回答