2016-08-30 2 views
0

를 사용하여 어린이 태그의 설명 텍스트를 얻을 방법이 클래스의 INGS '와 div 내가 내에서 데이터를 얻으려면 그 내가 코드를 아래에 쓴 것을위한 p 태그 :위의 페이지에서 <a href="http://www.foodily.com/r/0y1ygzt3zf-perfect-vanilla-cupcakes-by-annie-s" rel="nofollow noreferrer">foodily.com</a></p> <p>에서 나는 일부 데이터를 긁어 아름다운 수프를 사용하고 아름다운 수프

ingredients = soup.find('div', {"class": "ings"}).findChildren('p') 

그것은 나에게 성분의 목록을 제공하지만, p 태그.

답변

2

class="ings" 인 요소 내에있는 p 요소에 대해 get_text()을 호출하십시오.

전체 작업 코드 :

from bs4 import BeautifulSoup 
import requests 

with requests.Session() as session: 
    session.headers.update({"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36"}) 
    response = session.get("http://www.foodily.com/r/0y1ygzt3zf-perfect-vanilla-cupcakes-by-annie-s") 

    soup = BeautifulSoup(response.content, "html.parser") 

    ingredients = [ingredient.get_text() for ingredient in soup.select('div.ings p')] 
    print(ingredients) 

인쇄 : 나는 또한 당신의 로케이터 조금 개선하고 div.ings pCSS selector로 전환 한

[ 
    u'For the cupcakes:', 
    u'1 stick (113g) butter/marg*', 
    u'1 cup caster sugar', u'2 eggs', 
    ... 
    u'1 tbsp vanilla extract', 
    u'2-3tbsp milk', 
    u'Sprinkles to decorate, optional' 
] 

참고.

0

또 다른 방법 :

import requests 
from bs4 import BeautifulSoup as bs 


url = "http://www.foodily.com/r/0y1ygzt3zf-perfect-vanilla-cupcakes-by-annie-s" 
source = requests.get(url) 
text_new = source.text 
soup = bs(text_new, "html.parser") 
ingredients = soup.findAll('div', {"class": "ings"}) 
for a in ingredients : 
    print (a.text) 

그것은 인쇄됩니다 : 당신은 이미 p 태그의 목록이있는 경우

For the cupcakes: 

1 stick (113g) butter/marg* 

1 cup caster sugar 

2 eggs 

1 tbsp vanilla extract 

1 and 1/2 cups plain flour 

2 tsp baking powder 

1/2 cup milk (I use Skim) 

For the frosting: 

2 sticks (226g) unsalted butter, at room temp 

2 and 1/2 cups icing sugar, sifted 

1 tbsp vanilla extract 

2-3tbsp milk 

Sprinkles to decorate, optional 
0

get_text()를 사용합니다. 이것은 그들 만의 텍스트를 반환합니다

ingredient_list = [ 
    'For the cupcakes:', '1 stick (113g) butter/marg*', 
    '1 cup caster sugar','2 eggs', ... 
] 
:

ingredient_list = p.get_text() for p in ingredients 

결과 배열 모양을