当我使用的库使用不同的函数名称时,有没有更好的方法来解决硬编码兼容代码的问题?
另外,我无法更改库代码。(因为我使用的函数在旧版本的代码中是无处不在的)。该库是BeautifulSoup 3和4.请参阅http://www.crummy.com/software/BeautifulSoup/bs4/doc/
中的Method Name
部分
最初,我有bs4代码,但我的用户有bs3,所以我必须在下面放置以下代码:
try:
from bs4 import BeautifulSoup as bs
except:
from BeautifulSoup import BeautifulSoup as bs
page = '''<html>foo bar<p>blah blah black sheep</p> bar</html>'''
try:
p = bs(page).find_all('p')
except: # Imagine i have to do this all over my code that uses `find_all` or `findAll`
p = bs(page).findAll('p')
答案 0 :(得分:1)
可能你应该修补bs:
try:
from bs4 import BeautifulSoup as bs
except:
from BeautifulSoup import BeautifulSoup as bs
bs.find_all = getattr(bs, 'find_all', False) or getattr(bs, 'findAll')