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

或完全匹配任何东西,取决于网页。

4

2 回答 2

1

您可以eval用来评估存储在字符串中的任意 Python 表达式。然而,这是危险的。黑客或不道德的用户可以将恶意代码插入数据库(例如,1000000**1000000导致 Python 发疯)。

于 2013-03-17T08:01:21.480 回答
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 表达式。

例子:

来自数据库:

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

这样做:

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

我想你明白了主要的想法。

于 2013-03-17T10:13:55.553 回答