如何对包含格式字符的URL进行字符串插值?

3 投票
4 回答
2213 浏览
提问于 2025-04-16 06:14

我正在尝试使用 URLLIB2 打开一个网址,并把内容读入一个数组。问题似乎在于,网址中不能使用字符串插值,特别是当网址里有格式字符,比如 %20 代表空格,%3C 代表 '<' 时。这个网址里有空格和一些 XML 内容。

我的代码其实很简单,大概是这样的:

#Python script to fetch NS Client Policies using GUID

import sys
import urllib2

def GetPolicies(ns, guid):
    ns = sys.argv[1]
    guid = sys.argv[2]
    fetch = urllib2.urlopen('http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%3Crequest%20configVersion=%222%22%20guid=%22{%s}%22') % (ns, guid)

我把网址缩短了,但你大概能理解意思。你会遇到一个“格式字符串参数不够”的错误,因为它认为你想把 %3、%20 和其他的东西当作字符串插值来用。那怎么解决这个问题呢?

补充:解决方案需要 Python 2.6 及以上版本,2.5 或更早的版本不支持 string.format() 方法

4 个回答

0

如果你想自己构建网址,可以使用 urllib.urlencode。这个工具会帮你处理很多需要加引号的问题。你只需要把你想要的信息放进一个字典里传给它就可以了:

from urllib import urlencode

args = urlencode({'xml': '<',
           'request configVersion': 'bar',
               'guid': 'zomg'})

至于如何替换网址字符串中的主机名,按照大家说的做,使用 %s 格式化就可以了。最终的字符串可能会像这样:

print 'http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?%s' % ('foobar.com', args)
1

改用字符串的 .format 方法。根据它的说明:

str.format(*args, **kwargs) 
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'

虽然我们都习惯用 % 来格式化字符串,就像在C语言中那样,但其实 format 方法更强大,更可靠,可以把值插入到字符串里。

7

你可以把 % 符号写两遍

url = 'http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%%3Crequest%%20configVersion=%%222%%22%%20guid=%%22{%s}%%22' % (ns, guid)

或者你可以使用 .format() 方法

url = 'http://{hostname}/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%3Crequest%20configVersion=%222%22%20guid=%22{id}%%2''.format(hostname=ns, id=guid)

撰写回答