2017-12-30 26 views
1

Ich habe den folgenden HTML-Code mit BS4 erfasst, kann aber nicht nach dem Künstler-Tag suchen. ich diesen Codeblock einer Variablen zugewiesen haben Container, genannt und versucht dannSchöne Suppe Parse Python

print container.tr.td["artist"] 

ohne Glück. Irgendwelche Beratung geschätzt?

<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> 

Antwort

5

Ihre Syntax falsch ist, "Künstler" ist der Wert der "class" -Attribut versuchen Sie dies:

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()) 

Ausgänge:

kool as the gang 
2

Ein anderer Weg.

Suchen Sie nach dem Element innerhalb container, dessen class 'Künstler' mit der select Methode ist. Da es mehrere geben kann, aber Sie wissen, dass es nur einen gibt, wählen Sie das einzige Element in der Liste aus und fordern Sie das Attribut text an.

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