我正在编写一些BeautifulSoup代码来填充html页面结果中的字典,我需要一些错误处理。虽然我所做的工作让我觉得有更好的方法。这就是我所拥有的:
rightcol = result.find("div", {"class":"rightcol"})
try: mydict['rating'] = rightcol.find("div", {"class":"rating"}).contents[1]['class']
except AttributeError: pass
try: mydict['reviews'] = rightcol.find("span", {"class":"reviews"}).contents
except AttributeError: pass
try: mydict['address'] = rightcol.find("address").contents
except AttributeError: pass
(10+ more statements of the same kind)
我希望将错误处理放入一个函数中,例如:
def process(key, code):
try: mydict[key] = (execute the BeautifulSoup code, different for each function call)
except: pass
但是,我不确定如何将BeautifulSoup指令传递给函数的语法。有什么想法吗?
答案 0 :(得分:2)
您可以将函数放入dict
并在需要时调用它们:
def hello(name):
return 'Hello, ' + name
funcMap = {'greet' : hello}
greeting = funcMap['greet']('Peter')
print greeting # Hello, Peter
您可以在此处为此代码执行非常类似的操作。