AttributeError:' NoneType'对象没有属性' text' python 2.7

时间:2017-02-08 20:46:51

标签: python-2.7 beautifulsoup

我有一个用Python编写的简单网页抓取程序,用于查找配方的方法,但是当我运行代码时收到此错误消息:

  

AttributeError:' NoneType'对象没有属性' text'

我的代码:

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

2 个答案:

答案 0 :(得分:1)

  

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

页面上没有pclass="name"元素,这意味着name_boxNone

  

意在找到食谱的方法

对于配方方法,您可以使用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 :(得分:-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')