[英]How in Python can I call a function with a variable which is store as a string
I have problem similar to describe here , but a bit more complicated. 我有类似的问题要在这里描述,但要复杂一些。 There are BeautifulSoup objects (store in list) and I want to find some other tags.
有BeautifulSoup对象(存储在列表中),我想找到其他一些标签。 The information which tags I want to find are store in strings.
我要查找的标签信息存储在字符串中。 Ie:
即:
a= [...] #(list of BeautifulSoup objects)
next="findNext('span')"
b=[ getattr(c,next).string for c in a]
doesn't work. 不起作用。 What I do wrong.
我做错了。
Looks to me like what you want is: 在我看来您想要的是:
b = [ eval("c." + next).string for c in a ]
This will call findNext('span')
for each element c
of the list a
and form a list of the results of each findNext
call in the list b
. 这将为列表
a
每个元素c
调用findNext('span')
,并形成列表b
中每个findNext
调用的结果的列表。
Try 尝试
trees = [...] #(list of BeautifulSoup objects)
strings = [tree.findNext('span').string for tree in trees]
or, if you really must, 或者,如果您确实需要,
trees = [...] #(list of BeautifulSoup objects)
next = ('findNext', ('span',))
strings = [getattr(tree, next[0])(*(next[1])).string for tree in trees]
So I guess the next question is, what's a simple way to turn "findNext('span')"
into ('findNext', ('span',))
(keeping in mind that there may be multiple arguments)? 因此,我想下一个问题是,将
"findNext('span')"
转换为('findNext', ('span',))
的简单方法是什么(请记住可能有多个参数)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.