簡體   English   中英

如何在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM