2013-03-17 59 views
1

我看到答案,getattr()被用於一些簡單的方法/函數調用。如何運行任意字符串作爲命令

如何處理任意字符串在這裏做網頁解析:

from bs4 import BeautifulSoup 
import urllib 

f = urllib.urlopen(link) # link comes from database, e.g. 'http://www.example.com' 
soup = BeautifulSoup(f) 

text = soup.find(True, 'text').get_text() # Now this is hardcoded 

工作正常,但如何運行來自數據庫的解析器字符串?字符串可以是這樣的:

soup.find("div", "layout left").find(id=True).get_text() 

或漂亮的匹配任何東西,取決於網頁。

回答

1

您可以使用eval來評估存儲在字符串中的任意Python表達式。但是,這是危險的。黑客或不道德的用戶可能會將惡意代碼插入數據庫(例如,1000000**1000000導致Python陷入僵局)。

+0

謝謝,這就是解決方案!如你所說,必須考慮更多與安全相關的後果。 – MJo 2013-03-31 19:31:42

0

爲什麼不能從字符串行前進來構建一個列表並做類似這樣的事情?

tags = soup.findAll(['div','span']) 

soup.findAll(lambda tag: tag.name in ['div', 'span'] or tag['id'] == "eggs") 

,或者甚至更好:

tags = soup.findAll(['div', 'span']) 
tags.extend(soup.findAll(id="eggs")) 

如果你想排除條件一些標籤,你可以將條件添加到lambda表達式。

例子:

從DB:

s = 'div;span;table' # or something like this with structure 

這樣做:

tags_list = s.split(';') 
tags = soup.findAll(tags_list) 

我覺得你有主要的想法。

+0

我不確定我是否理解正確..但我試圖讓系統在哪裏可以很容易(不是編碼本身)添加新的網站和量身定製的字符串解析,所有這些只是通過花哨的UI插入數據到數據庫。 – MJo 2013-03-31 19:34:14

相關問題