【发布时间】:2014-09-23 15:32:46
【问题描述】:
我最近使用来自this question 的 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) 并且不再收到错误,但没有输出。是否有太多可能的原因无法猜测?
【问题讨论】:
-
他们
import BeautifulSoup,你from bs4 import BeautifulSoup。你应该使用bs = BeautifulSoup(data),或者import bs4然后bs = bs4.BeautifulSoup(data)。
标签: python beautifulsoup