我最近嘗試使用BeautifulSoup從this question以下的Python代碼,這似乎適用於提問者。運行BeautifulSoup時沒有輸出Python代碼
import urllib2
import bs4
import string
from bs4 import BeautifulSoup
badwords = set([
'cup','cups',
'clove','cloves',
'tsp','teaspoon','teaspoons',
'tbsp','tablespoon','tablespoons',
'minced'
])
def cleanIngred(s):
s=s.strip()
s=s.strip(string.digits + string.punctuation)
return ' '.join(word for word in s.split() if not word in badwords)
def cleanIngred(s):
# remove leading and trailing whitespace
s = s.strip()
# remove numbers and punctuation in the string
s = s.strip(string.digits + string.punctuation)
# remove unwanted words
return ' '.join(word for word in s.split() if not word in badwords)
def main():
url = "http://allrecipes.com/Recipe/Slow-Cooker-Pork-Chops-II/Detail.aspx"
data = urllib2.urlopen(url).read()
bs = BeautifulSoup.BeautifulSoup(data)
ingreds = bs.find('div', {'class': 'ingredients'})
ingreds = [cleanIngred(s.getText()) for s in ingreds.findAll('li')]
fname = 'PorkRecipe.txt'
with open(fname, 'w') as outf:
outf.write('\n'.join(ingreds))
if __name__=="__main__":
main()
我不能讓它在我的情況下工作,雖然由於某種原因。我收到錯誤:
AttributeError Traceback (most recent call last)
<ipython-input-4-55411b0c5016> in <module>()
41
42 if __name__=="__main__":
---> 43 main()
<ipython-input-4-55411b0c5016> in main()
31 url = "http://allrecipes.com/Recipe/Slow-Cooker-Pork-Chops-II/Detail.aspx"
32 data = urllib2.urlopen(url).read()
---> 33 bs = BeautifulSoup.BeautifulSoup(data)
34
35 ingreds = bs.find('div', {'class': 'ingredients'})
AttributeError: type object 'BeautifulSoup' has no attribute 'BeautifulSoup'
我懷疑這是因爲我使用bs4而不是BeautifulSoup。我嘗試用bs = bs4.BeautifulSoup(data)
替換行bs = BeautifulSoup.BeautifulSoup(data)
,不再收到錯誤,但沒有輸出。這種猜測有太多可能的原因嗎?
他們'進口BeautifulSoup',你'從BS4進口BeautifulSoup'。你應該使用'bs = BeautifulSoup(data)',或'import bs4',然後'bs = bs4.BeautifulSoup(data)'。 – jonrsharpe 2014-09-23 15:34:02