Недавно я попробовал следующий код Python с помощью BeautifulSoup от 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 = BeautifulSoup.BeautifulSoup(data)
на bs = bs4.BeautifulSoup(data)
и больше не получать сообщение об ошибке, но не получать вывод. Есть ли слишком много возможных причин для этого?
Они 'импорта BeautifulSoup', вы' от BS4 импорта BeautifulSoup'. Вы должны использовать 'bs = BeautifulSoup (data)' или 'import bs4', затем' bs = bs4.BeautifulSoup (data) '. – jonrsharpe