如何使用 request.get() 将参数传递给函数
所以这是我的原始代码
def get_xml():
xml = requests.get("http://charts.com/charts/101.xml").text
return xml
print get_xml()
上面的这段代码可以满足我的需要,但是我怎样才能用 x 替换“101”。 我试图用 url 变量替换我的地址,但我得到了 typeError 。请指教。
def get_xml(x):
url = "http://charts.com/charts/" + x + ".xml"
xml = requests.get(url).text
return xml
print get_xml(101)
最佳答案
Python 是一种强类型语言。这意味着它不知道如何添加整数和字符串:
>>> "5" + 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
在您的例子中,101
是一个整数。
您可以尝试使用字符串作为参数调用 get_xml
函数:
print get_xml("101")
或者在尝试连接之前将参数(在函数内部)转换(强制转换)为字符串(第二个选项可能更好,因为这样你的函数就可以正常工作 x
是 int
或 str
,并且不依赖于调用 get_xml
函数的程序员的善意:
url = "http://charts.com/charts/" + str(x) + ".xml"
或:
url = "http://charts.com/charts/%s.xml" % x
(对于最后一个,检查 this link )
关于python - 如何传递传递参数以从 xml request.get python 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18836537/