2017-05-14 95 views
0

我在使用beautifulsoup來刮一些信息的python.org網站。我也試圖讓程序打印的返回類型的函數nameerror while using eval with beautifulsoup

我的代碼如下:

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__ 

我想檢索字符串格式的功能,並把它傳遞給評估和獲得使用.__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

您需要在上面

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 ' 
+0

由於進口string。有其他選擇嗎? –

+1

沒有導入字符串? 'getattr(import_module(func_name.split(「。」)[0]),func_name.split(「。」)[1]).__ doc__'使用'from importlib import import_module ' – itzMEonTV

+0

Thanks that is what I wanted。任何想法如何獲得輸入參數的類型? –