需要在python中解析GET请求之类的东西

2024-09-30 03:25:06 发布

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

我有一个GET请求类型的字符串,我需要用python解析它。你知道吗

blahdeblahdeblah?query=This is the query&time=8:30

有没有人知道如何提取我想要的字符串,这样我就可以做类似的事情

query= This is the query
time= 8:30

请记住,我的一些弦可能没有时间。比如说

blahdeblahdeblah?query=This is a query without a time

我也需要处理。我怎么能这么做?我不确定像splitstring这样的东西是否适用于此,因为可以选择是否有一些变量。你知道吗


Tags: the字符串类型gettimeis时间this
2条回答
import re
val = 'blahdeblahdeblah?query=This is the query&time=8:30'
val = re.sub('.time=\d{1,3}\D\d{1,3}', '', val)

print val

使用urlparse.urlparse()(“将URL解析为六个组件,返回一个6元组。这与URL的一般结构相对应:scheme://netloc/path;参数?query#fragment.”)和urlparse.parse_qs()(“解析作为字符串参数给出的查询字符串(数据类型为application/x-www-form-urlencoded)。数据作为字典返回。字典键是唯一的查询变量名,值是每个名称的值列表。“)

>>> from urlparse import urlparse
>>> from urlparse import parse_qs
>>> urlparse('http//www.domain.com/path?a=1&b=2')
ParseResult(scheme='http', netloc='www.domain.com', path='/path', params='', query='a=1&b=2', fragment='')
>>> parse_result = urlparse('//www.domain.com/path?a=1&b=2')
>>> parse_qs(parse_result[4])
{'a': ['1'], 'b': ['2']}

您的示例可以如下所示:

>>> for k,x in parse_qs(urlparse('blahdeblahdeblah?query=This is the query&time=8:30')[4]).items():
...     print '%s=%s' % (k, x)
...
query=['This is the query']
time=['8:30']

有关urlparseparse_qs,请参阅Python文档

相关问题 更多 >

    热门问题