开发者

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. The information which tags I want to find are store in strings. I.e.:

a= [...] #(list of BeautifulSoup objects)
next="findNext('span')"

b=[ getattr(c,next)开发者_JAVA百科.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.


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)?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜