2011-03-25 107 views
0

我有類似描述here的問題,但有點複雜。有BeautifulSoup對象(在列表中存儲),我想找到一些其他標籤。我想要查找的標籤信息以字符串形式存儲。 I.e .:如何在Python中使用存儲爲字符串的變量調用函數

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

b=[ getattr(c,next).string for c in a] 

不起作用。我做錯了什麼。

+2

您是否收到錯誤消息或輸出錯誤?你能舉一個例子嗎? 「不起作用」對你的問題沒有太大幫助。 – 2011-03-25 01:45:49

+0

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

回答

1

在我看來就像你想要的是:

b = [ eval("c." + next).string for c in a ] 

這將調用findNext('span')的名單a的每個元素c,然後在列表b形成每個findNext調用的結果列表。

+0

我做了一個測試,它似乎做我的預期。非常感謝。 – Wawrzek 2011-03-26 00:28:25

0

嘗試

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',))(記住,可能有一個簡單的方法是多個參數)?

+0

問題是,「findNext('span')」就是一個例子,它會隨着頁面的變化而變化。我打算從數據庫(或字典)中讀取它。我想這會解決你的擔憂,不是嗎? – Wawrzek 2011-03-26 00:38:00