Retrieving parameters from a URL

2019-01-04 08:40发布

Given a URL like the following, how can I parse the value of the query parameters? For example, in this case I want the value of def.

/abc?def='ghi'

I am using Django in my environment; is there a method on the request object that could help me?

I tried using self.request.get('def') but it is not returning the value ghi as I had hoped.

14条回答
ゆ 、 Hurt°
2楼-- · 2019-01-04 08:57

There is a nice library w3lib.url

from w3lib.url import url_query_parameter
url = "/abc?def=ghi"
print url_query_parameter(url, 'def')
ghi
查看更多
叼着烟拽天下
3楼-- · 2019-01-04 09:01
import cgitb
cgitb.enable()

import cgi
print "Content-Type: text/plain;charset=utf-8"
print
form = cgi.FieldStorage()
i = int(form.getvalue('a'))+int(form.getvalue('b'))
print i
查看更多
太酷不给撩
4楼-- · 2019-01-04 09:03

I know this is a bit late but since I found myself on here today, I thought that this might be a useful answer for others.

import urlparse
url = 'http://example.com/?q=abc&p=123'
parsed = urlparse.urlparse(url)
params = urlparse.parse_qsl(parsed.query)
for x,y in params:
    print "Parameter = "+x,"Value = "+y

With parse_qsl(), "Data are returned as a list of name, value pairs."

查看更多
老娘就宠你
5楼-- · 2019-01-04 09:07

Try with something like this:

import urlparse
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print urlparse.parse_qs(parsed.query)['def']
查看更多
唯我独甜
6楼-- · 2019-01-04 09:08
def getParams(url):
    params = url.split("?")[1]
    params = params.split('=')
    pairs = zip(params[0::2], params[1::2])
    answer = dict((k,v) for k,v in pairs)

Hope this helps

查看更多
对你真心纯属浪费
7楼-- · 2019-01-04 09:08

The urlparse module provides everything you need:

urlparse.parse_qs()

查看更多
登录 后发表回答