简体   繁体   English

如何在Python中调用带有存储为字符串的变量的函数

[英]How in Python can I call a function with a variable which is store as a string

I have problem similar to describe here , but a bit more complicated. 我有类似的问题要在这里描述,但要复杂一些。 There are BeautifulSoup objects (store in list) and I want to find some other tags. 有BeautifulSoup对象(存储在列表中),我想找到其他一些标签。 The information which tags I want to find are store in strings. 我要查找的标签信息存储在字符串中。 Ie: 即:

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

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

doesn't work. 不起作用。 What I do wrong. 我做错了。

Looks to me like what you want is: 在我看来您想要的是:

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

This will call findNext('span') for each element c of the list a and form a list of the results of each findNext call in the list b . 这将为列表a每个元素c调用findNext('span') ,并形成列表b中每个findNext调用的结果的列表。

Try 尝试

trees = [...] #(list of BeautifulSoup objects)
strings = [tree.findNext('span').string for tree in trees]

or, if you really must, 或者,如果您确实需要,

trees = [...] #(list of BeautifulSoup objects)
next = ('findNext', ('span',))
strings = [getattr(tree, next[0])(*(next[1])).string for tree in trees]

So I guess the next question is, what's a simple way to turn "findNext('span')" into ('findNext', ('span',)) (keeping in mind that there may be multiple arguments)? 因此,我想下一个问题是,将"findNext('span')"转换为('findNext', ('span',))的简单方法是什么(请记住可能有多个参数)?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我有一个带有函数名称的字符串变量,如何在Python中调用该函数? - i have a string variable which comes with function names, how do I call the function in Python? 如何将存储在变量中的函数结果存储为字符串? - How can I store the result of a function stored in variable as a string? 如何将某些内容附加到函数的结果中并将其存储在python中的变量中 - How can I append something to a result of a function and store that in a Variable in python 如何确定要在python中定义的函数使用哪个变量 - How can I determine which variable to use for a defined function in python 如何调用 function 打印在另一个 function 中定义的字符串变量? - How do I call a function that prints a string variable which is defined in another function? Django:如何将在随机函数中生成的变量存储在数据库中? - Django: How can I store in database a variable which I generate in a random function? python:如何仅使用字符串名称将变量传递给函数 - python: how can I pass a variable to a function with only the string name 如何使用 python 将字符串中的元素相乘并将结果字符串存储在变量中? - How can I multiply elements in a string using python and store resulting string in a variable? 如何将文件路径存储在可以在其他函数中使用的变量中? - How to store file path in variable which can use in other function? 如何从另一个重新定义的 python 文件中调用变量 - How can I call a variable from another python file which is re-defined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM