2017-02-08 2 views
0

У меня есть простая программа для очистки веб-страниц, написанная на Python, которая предназначена для поиска метода для рецепта, однако я получаю это сообщение об ошибке при запуске кода: «AttributeError: объект« NoneType »не имеет атрибута« текст ».AttributeError: объект «NoneType» не имеет атрибута «text» python 2.7

from bs4 import BeautifulSoup 
import urllib2 

quote_page = 'http://www.foodnetwork.co.uk/recipes/easy-pan-roasted-chicken-and-shallots.html' 
page = urllib2.urlopen(quote_page) 
soup = BeautifulSoup(page, 'html.parser') 
name_box = soup.find('p', attrs={'class': 'name'}) 
name = name_box.text.strip() # strip() is used to remove starting and trailing 
print name 
+0

Очевидно 'name_box является None'. – jonrsharpe

ответ

0

AttributeError: 'NoneType' object has no attribute 'text'

Там нет p элемента с class="name" на странице, что означает это name_box есть None.

meant to find the method for a recipe

Для метода рецепта, вы можете использовать recipeInstructions itemprop значение атрибута:

instructions = soup.find("div", itemprop="recipeInstructions") 
print(instructions.get_text(strip=True)) 

Демо:

>>> from bs4 import BeautifulSoup 
>>> import urllib2 
>>> 
>>> quote_page = 'http://www.foodnetwork.co.uk/recipes/easy-pan-roasted-chicken-and-shallots.html' 
>>> page = urllib2.urlopen(quote_page) 
>>> soup = BeautifulSoup(page, 'html.parser') 
>>> 
>>> instructions = soup.find("div", itemprop="recipeInstructions") 
>>> print(instructions.get_text(strip=True)) 
Preheat the oven to 220°C. Sprinkle both sides of the chicken breasts with salt and pepper.Preheat a large, oven-safe frying pan over medium-high heat for 2 minutes. Working quickly, melt 1 tablespoon of the butter, swirling it around the pan. Add the chicken, skin side down. Add the shallots, cut side down and not overlapping. Cook until the chicken and shallots are browned on the bottom, 2 to 3 minutes. Flip the shallots and chicken, nestle in the rosemary sprigs, then carefully pour in the chicken stock.Transfer the frying pan to the oven and roast until the chicken is cooked through and the shallots are tender, 12 to 14 minutes, removing the smaller pieces of chicken first as they become cooked. Transfer the chicken to a serving plate.Check the frying pan with the shallots to make sure the stock has not evaporated; if less than a few tablespoons remain, add 1/2 cup more stock or water. Reduce the pan juices over medium heat until about 1/2 cup of liquid remains, about 2 minutes. Remove the frying pan from the heat and stir in the remaining 2 tablespoons of butter with a wooden spoon to thicken the pan sauce until it coats the spoon. Remove the rosemary and season the sauce with salt and pepper. Spoon some of the sauce over the chicken and shallots and the rest onto the plate.Copyright 2014 Television Food Network, G.P. All rights reserved. 
-1

Вы должны извлечь text содержимого из HTTP ответа и анализировать, что

Используйте .read()

quote_page = 'http://www.foodnetwork.co.uk/recipes/easy-pan-roasted-chicken-and-shallots.html' 
page = urllib2.urlopen(quote_page) 
soup = BeautifulSoup(page.read(), 'html.parser') 
+0

BeautifulSoup будет вызывать '.read()' неявно. [Он поддерживается] (https://www.crummy.com/software/BeautifulSoup/bs4/doc/#making-the-soup). – alecxe

+0

Никогда не знал этого. Спасибо –