如何在Python中使用存储为字符串的变量调用函数
我有类似描述here的问题,但有点复杂。有BeautifulSoup对象(在列表中存储),我想找到一些其他标签。我想要查找的标签信息以字符串形式存储。 I.e .:如何在Python中使用存储为字符串的变量调用函数
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 ]
这将调用findNext('span')
的名单a
的每个元素c
,然后在列表b
形成每个findNext
调用的结果列表。
我做了一个测试,它似乎做我的预期。非常感谢。 – Wawrzek 2011-03-26 00:28:25
尝试
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',))
(记住,可能有一个简单的方法是多个参数)?
问题是,“findNext('span')”就是一个例子,它会随着页面的变化而变化。我打算从数据库(或字典)中读取它。我想这会解决你的担忧,不是吗? – Wawrzek 2011-03-26 00:38:00
您是否收到错误消息或输出错误?你能举一个例子吗? “不起作用”对你的问题没有太大帮助。 – 2011-03-25 01:45:49
next ='findNext(“span”)' compare a1 = [getattr(c,next)for a.atags] to a2 = [c.findNext(“span”)for a.atags] a1 [0] =无当a2 [0] = Linguamatics 所以它确实有效,只是不像预期的那样。 – Wawrzek 2011-03-26 00:21:32