问题:从URL检索参数

给定如下所示的URL,如何解析查询参数的值?例如,在这种情况下,我需要的值def

/abc?def='ghi'

我在我的环境中使用Django;有没有一种方法request可以帮助我?

我尝试使用,self.request.get('def')但是它没有返回ghi我希望的值。

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.


回答 0

Python 2:

import urlparse
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print urlparse.parse_qs(parsed.query)['def']

Python 3:

import urllib.parse as urlparse
from urllib.parse import parse_qs
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print(parse_qs(parsed.query)['def'])

parse_qs返回值列表,因此上述代码将打印['ghi']

这是Python 3文档。

Python 2:

import urlparse
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print urlparse.parse_qs(parsed.query)['def']

Python 3:

import urllib.parse as urlparse
from urllib.parse import parse_qs
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print(parse_qs(parsed.query)['def'])

parse_qs returns a list of values, so the above code will print ['ghi'].

Here’s the Python 3 documentation.


回答 1

我很震惊这个解决方案还没有在这里。用:

request.GET.get('variable_name')

这将从“ GET”字典中“获取”变量,并返回“ variable_name”值(如果存在),或者返回None对象(如果不存在)。

I’m shocked this solution isn’t on here already. Use:

request.GET.get('variable_name')

This will “get” the variable from the “GET” dictionary, and return the ‘variable_name’ value if it exists, or a None object if it doesn’t exist.


回答 2

import urlparse
url = 'http://example.com/?q=abc&p=123'
par = urlparse.parse_qs(urlparse.urlparse(url).query)

print par['q'][0], par['p'][0]
import urlparse
url = 'http://example.com/?q=abc&p=123'
par = urlparse.parse_qs(urlparse.urlparse(url).query)

print par['q'][0], par['p'][0]

回答 3

对于Python> 3.4

from urllib import parse
url = 'http://foo.appspot.com/abc?def=ghi'
query_def=parse.parse_qs(parse.urlparse(url).query)['def'][0]

for Python > 3.4

from urllib import parse
url = 'http://foo.appspot.com/abc?def=ghi'
query_def=parse.parse_qs(parse.urlparse(url).query)['def'][0]

回答 4

有一个名为furl的新库。我发现这个库是执行url代数的最pythonic。安装:

pip install furl

码:

from furl import furl
f = furl("/abc?def='ghi'") 
print f.args['def']

There is a new library called furl. I find this library to be most pythonic for doing url algebra. To install:

pip install furl

Code:

from furl import furl
f = furl("/abc?def='ghi'") 
print f.args['def']

回答 5

我知道这有点晚了,但是自从我今天在这里找到自己以来,我认为这对其他人可能是一个有用的答案。

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

使用parse_qsl(),“将数据作为名称,值对的列表返回。”

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.”


回答 6

您引用的url是一种查询类型,我看到请求对象支持一种称为arguments的方法来获取查询参数。您可能还希望self.request.get('def')直接尝试从对象中获取价值。

The url you are referring is a query type and I see that the request object supports a method called arguments to get the query arguments. You may also want try self.request.get('def') directly to get your value from the object..


回答 7

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)

希望这可以帮助

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


回答 8

urlparse模块提供您所需的一切:

urlparse.parse_qs()

The urlparse module provides everything you need:

urlparse.parse_qs()


回答 9

不需要做任何事情。只有

self.request.get('variable_name')

注意,我没有指定方法(GET,POST等)。这是有据可查的这是一个示例

您使用Django模板的事实并不意味着处理程序也由Django处理

There’s not need to do any of that. Only with

self.request.get('variable_name')

Notice that I’m not specifying the method (GET, POST, etc). This is well documented and this is an example

The fact that you use Django templates doesn’t mean the handler is processed by Django as well


回答 10

在纯Python中:

def get_param_from_url(url, param_name):
    return [i.split("=")[-1] for i in url.split("?", 1)[-1].split("&") if i.startswith(param_name + "=")][0]

In pure Python:

def get_param_from_url(url, param_name):
    return [i.split("=")[-1] for i in url.split("?", 1)[-1].split("&") if i.startswith(param_name + "=")][0]

回答 11

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
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

回答 12

顺便说一句,我在使用parse_qs()并获取空值参数时遇到了问题,并了解到您必须传递第二个可选参数’keep_blank_values’才能在查询字符串中返回不包含任何值的参数列表。默认为false。某些糟糕的书面API要求参数存在,即使它们不包含任何值

for k,v in urlparse.parse_qs(p.query, True).items():
  print k

Btw, I was having issues using parse_qs() and getting empty value parameters and learned that you have to pass a second optional parameter ‘keep_blank_values’ to return a list of the parameters in a query string that contain no values. It defaults to false. Some crappy written APIs require parameters to be present even if they contain no values

for k,v in urlparse.parse_qs(p.query, True).items():
  print k

回答 13

有一个不错的库w3lib.url

from w3lib.url import url_query_parameter
url = "/abc?def=ghi"
print url_query_parameter(url, 'def')
ghi

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

回答 14

参数= dict([part.split(’=’)代表get_parsed_url [4] .split(’&’)]的部分)

这很简单。可变参数将包含所有参数的字典。

parameters = dict([part.split(‘=’) for part in get_parsed_url[4].split(‘&’)])

This one is simple. The variable parameters will contain a dictionary of all the parameters.


回答 15

我看到龙卷风用户没有答案:

key = self.request.query_arguments.get("key", None)

此方法必须在派生自以下对象的处理程序中起作用:

tornado.web.RequestHandler

当找不到所请求的密钥时,此方法将返回的答案是无。这为您节省了一些异常处理。

I see there isn’t an answer for users of Tornado:

key = self.request.query_arguments.get("key", None)

This method must work inside an handler that is derived from:

tornado.web.RequestHandler

None is the answer this method will return when the requested key can’t be found. This saves you some exception handling.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。