使用eval与beautifulsoup时的名字错误

时间:2017-05-14 20:03:26

标签: python beautifulsoup eval

我正在使用 beautifulsoup 在python.org网站上搜索一些信息。我也试图让程序打印函数的返回类型

我的代码如下:

soup = Soup(gethtml('https://docs.python.org/3/library/string.html'))
for function in soup.find_all('dl', {'class': 'function'}):
    try:
        func_name = function.dt['id']
        print eval(func_name).__doc__

我正在尝试以字符串格式检索函数并将其传递给eval并使用.__doc__获取返回信息

在这种情况下是string.capwords

但是,我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/GX70/PycharmProjects/assignment/tasks/libscrape.py", line 58, in <module>
    print eval(func_name).__doc__
  File "<string>", line 1, in <module>
NameError: name 'string' is not defined

1 个答案:

答案 0 :(得分:1)

您需要在顶部

导入string
import string

然后

In [165]: eval("string.capwords.__doc__")
Out[165]: 'capwords(s [,sep]) -> string\n\n    Split the argument into words using split, capitalize each\n    word using capitalize, and join the capitalized words using\n    join.  If the optional second argument sep is absent or None,\n    runs of whitespace characters are replaced by a single space\n    and leading and trailing whitespace are removed, otherwise\n    sep is used to split and join the words.\n\n    '