2017-12-17 6 views
0

MacとBeautifulSoupのPython3.6で実験しています。 URLから曲の歌詞を取り除き、プレーンテキストとして単一の変数に格納する簡単なプログラムを作成しようとしていますが、HTMLコンテンツを繰り返し処理することはできません。BeautifulSoupを使ってリストを反復することができません

:私は、私は次のエラーを取得する all = all.textをしようとする場合には、コードの最後の2行は、また "List index out of range" Error

を返す

import requests 
import re 
from bs4 import BeautifulSoup 

r = requests.get("http://www.metrolyrics.com/juicy-lyrics-notorious-big.html") 
c = r.content 

all = soup.find_all("p",{"class":"verse"}) 
all[0:10] 

for item in all: 
    print(item.find_all("p",{"class":"verse"})[0].text) 

を:

この

は私が実行しているコードです。
AttributeError: ResultSet object has no attribute 'text'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()? 

これは単純なものだが、もう何をすべきかわからないと思う。

おかげ

答えて

2

ループ内itemはBeautifulSoupタグが(: - > <class 'bs4.element.Tag'>type(all[0])でそれを確認してください)です。

for item in all: 
    print(item.text) 

を、変数allが10より短い場合、それは範囲外のエラーが発生します:

だから、そこから直接テキストを抽出することができます。

+0

うわー、それは本当に簡単でした。ありがとうございました! –

関連する問題