![](/img/trans.png)
[英]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.