[英]i have a string variable which comes with function names, how do I call the function in Python?
[英]How in Python can I call a function with a variable which is store as a string
我有类似的问题要在这里描述,但要复杂一些。 有BeautifulSoup对象(存储在列表中),我想找到其他一些标签。 我要查找的标签信息存储在字符串中。 即:
a= [...] #(list of BeautifulSoup objects)
next="findNext('span')"
b=[ getattr(c,next).string for c in a]
不起作用。 我做错了。
在我看来您想要的是:
b = [ eval("c." + next).string for c in a ]
这将为列表a
每个元素c
调用findNext('span')
,并形成列表b
中每个findNext
调用的结果的列表。
尝试
trees = [...] #(list of BeautifulSoup objects)
strings = [tree.findNext('span').string for tree in trees]
或者,如果您确实需要,
trees = [...] #(list of BeautifulSoup objects)
next = ('findNext', ('span',))
strings = [getattr(tree, next[0])(*(next[1])).string for tree in trees]
因此,我想下一个问题是,将"findNext('span')"
转换为('findNext', ('span',))
的简单方法是什么(请记住可能有多个参数)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.