私は、複数の引数をとり、呼び出し可能なラムダ関数を返す関数を作成しようとしています。私は、これらのラムダ関数をBeautifulSoupのfind_all
メソッドに渡して、htmlを解析しています。ここで動的に作成された関数を返す
は、私はラムダ関数を生成するために書いた関数である。
def tag_filter_function(self, name="", search_terms={}, attrs=[], **kwargs):
# filter attrs that are in the search_terms keys out of attrs
attrs = [attr for attr in attrs if attr not in search_terms.keys()]
# array of strings to compile into a lambda function
exec_strings = []
# add name search into exec_strings
if len(name) > 0:
tag_search_name = "tag.name == \"{}\"".format(name)
exec_strings.append(tag_search_name)
# add generic search terms into exec_strings
if len(search_terms) > 0:
tag_search_terms = ' and '.join(["tag.has_attr(\"{}\") and tag[\"{}\"] == \"{}\"".format(k, k, v) for k, v in search_terms.items()])
exec_strings.append(tag_search_terms)
# add generic has_attr calls into exec_strings
if len(attrs) > 0:
tag_search_attrs = ' and '.join(["tag.has_attr(\"{}\")".format(item) for item in attrs])
exec_strings.append(tag_search_attrs)
# function string
exec_string = "lambda tag: " + " and ".join(exec_strings)
return exec(compile(exec_string, '<string>', 'exec'))
tag_filter_function(name="article", search_terms={"id" : "article"})
を呼び出してから返す関数文字列が
lambda tag: tag.name == "article" and tag.has_attr("id") and tag["id"] == "article"
関数の戻りです値はNone
です。私は、exec()
機能が私がここで使用したい機能であると確信していませんが、私は本当にわかりません。この文字列を実行可能なラムダ関数に変換できますか?これについて正しいことをやっているかどうかはわかりません。
あなたがタグに 'has_attr'を使用している場合は、あなたがtag.attr'を探してはいけません:あなたはこのような何かをしたいようなあなたの場合には
は、それが見えます'tag [attr]ではなく? –