2017-05-14 1 views
0

Je suis en train de gratter le site python.org pour obtenir quelques infos en utilisant beautifulsoup. Je tente aussi d'obtenir le programme d'imprimer le type de retour d'une fonctionnomerror lors de l'utilisation eval avec beautifulsoup

Mon code est le suivant:

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__ 

Je suis en train de récupérer la fonction sous forme de chaîne et de la transmettre à eval et obtenir l'info de retour à l'aide .__doc__

qui dans ce cas est string.capwords

Cependant, je reçois l'erreur suivante:

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 

Répondre

1

Vous devez importer string sur

import string 

Puis

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

Merci. Y a-t-il une alternative? –

+1

sans chaîne d'importation? 'getattr (import_module (nom_fonction.split (". ") [0]), nom_fonction.split (". ") [1]) .__ doc__' pour utiliser' depuis importlib import import_module ' – itzMEonTV

+0

Merci, c'est ce que je voulais. Une idée de comment obtenir des types de paramètres d'entrée? –