将变量值插入URL(或任何字符串)

时间:2015-05-12 20:30:05

标签: python json urllib

我目前正在使用/usr/bin/zsh <<'EOF' git clone --recursive https://github.com/sorin-ionescu/prezto.git "${ZDOTDIR:-$HOME}/.zprezto" setopt EXTENDED_GLOB for rcfile in "${ZDOTDIR:-$HOME}"/.zprezto/runcoms/^README.md(.N); do ln -s "$rcfile" "${ZDOTDIR:-$HOME}/.${rcfile:t}" done chsh -s /bin/zsh EOF urllib对REST API执行JSON请求,如下所示:

json

我正在与之交互的API具有以下功能:如果import urllib, json url = "http://www.cvedetails.com/json-feed.php?numrows=5&vendor_id=26&product_id=0&version_id=0&hasexp=1&opec=1&opov=1&opcsrf=1&opfileinc=1&opgpriv=0&opsqli=1&opxss=0&opdirt=0&opmemc=0&ophttprs=0&opbyp=0&opginf=0&opdos=0&orderby=0&cvssscoremin=0" response = urllib.urlopen(url) data = json.loads(response.read()) for index, entry in enumerate(data, 1): print ('Item {}'.format(index)) for name, value in entry.items(): print '{}: {}'.format(name, value) vendor_id被更改,则值将意味着更改为供应商和产品执行的查找,从而产生不同的响应生成。

我想知道是否可以通过product_id函数或类似操作在url字符串中注入和更改vendor_idproduct_id数字,用户可以输入这两个数值都是?在这种情况下,raw_input运算符的使用是否不正确,因为这是为字符串注入字符串?

1 个答案:

答案 0 :(得分:0)

字符串操作很简单:

vendor_id = raw_input("Vendor ID: ")
product_id = raw_input("Product ID: ")
url = ("http://www.cvedetails.com/json-feed.php?"
       "numrows=5"
       "&vendor_id={0}"
       "&product_id={1}"
       "&version_id=0"
       "&hasexp=1"
       "&opec=1"
       "&opov=1"
       "&opcsrf=1"
       "&opfileinc=1"
       "&opgpriv=0"
       "&opsqli=1"
       "&opxss=0"
       "&opdirt=0"
       "&opmemc=0"
       "&ophttprs=0"
       "&opbyp=0"
       "&opginf=0"
       "&opdos=0"
       "&orderby=0"
       "&cvssscoremin=0"
       .format(vendor_id, product_id))

>>> url
'http://www.cvedetails.com/json-feed.php?numrows=5&vendor_id=26&product_id=0&version_id=0&hasexp=1&opec=1&opov=1&opcsrf=1&opfileinc=1&opgpriv=0&opsqli=1&opxss=0&opdirt=0&opmemc=0&ophttprs=0&opbyp=0&opginf=0&opdos=0&orderby=0&cvssscoremin=0'