2017-12-30 43 views
1

私はBS4を使って以下のhtmlをキャプチャしましたが、アーティストタグを検索できないようです。 私はコンテナという変数にコードブロックを割り当てられ、その後、運なしBeautiful Soup Parse Python

print container.tr.td["artist"] 

を試してみました。 アドバイスありがとうございます。

<tr class="item"> 
    <!-- <td class="image"><a href="https://www.stargreen.com/kool-as-the-gang-44415.html" title="KOOL AS THE GANG " class="product-image"><img src="https://www.stargreen.com/media/catalog/product/cache/1/small_image/135x/9df78eab33525d08d6e5fb8d27136e95/K/o/KoolAsTheGang.jpg" width="135" height="135" alt="KOOL AS THE GANG " /></a></td> --> 
    <td class="date">Sat, 30 Dec 2017</td> 
    <td class="artist">kool as the gang</td> 
    <td class="venue">100 club</td> 
    <td class="link"> 
    <p class="availability out-of-stock"> 
    <span>Off Sale</span></p> 
    </td> 
</tr> 

答えて

5

あなたの構文が間違っている、 "アーティスト" "クラス" の値は、この試す属性れる:

from bs4 import BeautifulSoup 

html = """ 
<tr class="item"> 
<!-- <td class="image"><a href="https://www.stargreen.com/kool-as-the-gang-44415.html" title="KOOL AS THE GANG " class="product-image"><img src="https://www.stargreen.com/media/catalog/product/cache/1/small_image/135x/9df78eab33525d08d6e5fb8d27136e95/K/o/KoolAsTheGang.jpg" width="135" height="135" alt="KOOL AS THE GANG " /></a></td> --> 
<td class="date">Sat, 30 Dec 2017</td> 
<td class="artist"> 
         kool as the gang      </td> 
<td class="venue">100 club</td> 
<td class="link"> 
<p class="availability out-of-stock"> 
<span>Off Sale</span></p> 
</td> 
</tr> 
""" 

soup = BeautifulSoup(html, 'html.parser') 
td = soup.find('td',{'class': 'artist'}) 
print (td.text.strip()) 

出力:

kool as the gang 
2

別の方法を。

containerの中のclassが「アーティスト」の要素をselectメソッドで探します。複数ある可能性があるので、1つしかないことがわかっているので、リスト内の唯一の要素を選択し、そのtext属性を要求します。

>>> HTML = open('sven.htm').read() 
>>> import bs4 
>>> container = bs4.BeautifulSoup(HTML, 'lxml') 
>>> container.select('.artist')[0].text 
'\n      kool as the gang      ' 
関連する問題