2017-10-22 10 views
0
h1 = soup.find('a', {'class': 'lien-jv topic-title'})['title'] 
print (h1) 

タイトルタグにある値をsoup.find関数で取得するのに問題はありませんでした。 しかし、私は解析しているページにそのような複数のタグがあるので、私はsoup.find_all関数を使用する必要があり、それは動作していません。このコードPython&BeautifulSoup:soup.find_allの問題

h1 = soup.find_all('a', {'class': 'lien-jv topic-title'})['title'] 
    print (h1) 

私はこのエラーに助けを

Traceback (most recent call last): 
    File "<tmp 1>", line 8, in <module> 
    h1 = soup.find_all('a', {'class': 'lien-jv topic-title'})['title'] 
TypeError: list indices must be integers, not str 

感謝していました。

+0

は '、あなたはすべてのタグのタイトルが必要なのでしょうか? – PRMoureu

+0

はい、私はすべてのタグのタイトルが必要です! – Diamonds

答えて

2

この作業をする必要があります:あなたはfind_all機能を使用すると、classであなたのケースでは、フィルタ処理ていることにより、soupオブジェクトのリストを返すということを覚えておいてください

results = [a['title'] for a in soup.find_all('a', {'class': 'lien-jv topic-title'})] 
1

。あなたがやろうとして隣は何

は次のとおりです。

h1 = soup.find_all('a', {'class': 'lien-jv topic-title'})['title'] soup.find_all('a', {'class': 'lien-jv topic-title'})はリストであり、あなたは間違っている['title']にアクセスしようとしています。

soからtitleを受信するための最良の方法:リストを返すfind_all`

titles = map(lambda soup_object: soup_object['title'], soup.find_all('a', {'class': 'lien-jv topic-title'}))