2014-09-23 2 views
0

Недавно я попробовал следующий код 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) и больше не получать сообщение об ошибке, но не получать вывод. Есть ли слишком много возможных причин для этого?

+2

Они 'импорта BeautifulSoup', вы' от BS4 импорта BeautifulSoup'. Вы должны использовать 'bs = BeautifulSoup (data)' или 'import bs4', затем' bs = bs4.BeautifulSoup (data) '. – jonrsharpe

ответ

1

Исходный код используется BeautifulSoup версия 3:

import BeautifulSoup 

Вы перешли на BeautifulSoup версии 4, но и переключил стиль импорта:

from bs4 import BeautifulSoup 

Либо удалите эту строку; у вас уже есть правильный импорт ранее в файле:

import bs4 

, а затем использовать:

bs = bs4.BeautifulSoup(data) 

или изменить эту последнюю линию:

bs = BeautifulSoup(data) 

(и удалить import bs4 линию) ,

Вы также можете просмотреть Porting code to BS4 section документации BeautifulSoup, так что вы можете сделать любые другие необходимые изменения, обновляющиеся код, который вы нашли, чтобы получить лучшее из BeautifulSoup версии 4.

Сценарий иначе работает просто отлично и создает новый файл, PorkRecipe.txt, он не выводит вывод на stdout.

Содержимое файла после фиксации bs4.BeautifulSoup ссылка:

READY IN 4+ hrs 

Slow Cooker Pork Chops II 

Amazing Pork Tenderloin in the Slow Cooker 

Jerre's Black Bean and Pork Slow Cooker Chili 

Slow Cooker Pulled Pork 

Slow Cooker Sauerkraut Pork Loin 

Slow Cooker Texas Pulled Pork 

Oven-Fried Pork Chops 

Pork Chops for the Slow Cooker 

Tangy Slow Cooker Pork Roast 

Types of Cooking Oil 

Garlic: Fresh Vs. Powdered 

All about Paprika 

Types of Salt 
olive oil 
chicken broth 
garlic, 
paprika 
garlic powder 
poultry seasoning 
dried oregano 
dried basil 
thick cut boneless pork chops 
salt and pepper to taste 
PREP 10 mins 
COOK 4 hrs 
READY IN 4 hrs 10 mins 
In a large bowl, whisk together the olive oil, chicken broth, garlic, paprika, garlic powder, poultry seasoning, oregano, and basil. Pour into the slow cooker. Cut small slits in each pork chop with the tip of a knife, and season lightly with salt and pepper. Place pork chops into the slow cooker, cover, and cook on High for 4 hours. Baste periodically with the sauce 
+0

@MaxPower: скрипт работает иначе; вам нужно проверить, что файл создан, а не на выходе. –

+0

@Martjin Большое спасибо, я должен быть более осторожным при использовании разных версий! –