Yan
Yan

Reputation: 1

python beautifulsoup parsing recursing

I'm a python/BeautifulSoup beginner, I'm trying to extract all the content in <td width="473" valign="top"> -> <strong>.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pl" lang="pl">
<head>
    <title>MIEJSKI OŚRODEK KULTURY W ŻORACH Repertuar Kina Na Starówce</title>
</head>
<body>
<div class="page_content">
<p>&nbsp;</p>
<p>
<table style="width: 450px;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="57" valign="top">
<p align="center"><strong>Data</strong></p>
</td>
<td width="473" valign="top">
<p align="center"><strong>Tytuł Filmu</strong></p>
</td>
<td width="95" valign="top">
<p align="center"><strong>Godzina</strong></p>
</td>
</tr>
<tr>
<td width="57" valign="top">
<p align="center"><strong>&nbsp;</strong></p>
</td>
<td width="473" valign="top">
<p align="center"><strong>1 - 5.05</strong></p>
</td>
<td width="95" valign="top">
<p align="center">&nbsp;</p>
</td>
</tr>
<tr>
<td width="57" valign="top">
<p align="center"><strong>1</strong></p>
</td>
<td width="473" valign="top">
<p align="center"><strong>KINO POWT&Oacute;REK: ZWIERZOGR&Oacute;D </strong>USA/b.o&nbsp; cena 10 zł</p>
</td>
<td width="95" valign="top">
<p align="center">16:30</p>
</td>
</tr>

</tbody>
</table>
</p>
</body>
</html>

The furthest I can go is to get a list of all the tags with this code:

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("zory1.html"), "html.parser")

y = soup.find_all(width="473")

newy = str(y)

newsoup = BeautifulSoup(newy ,"html.parser")
stronglist = newsoup.find_all('strong')

lasty = str(stronglist)

lastsoup = BeautifulSoup(lasty , "html.parser")

lst = soup.find_all('strong')

for item in lst:
    print item

How can I take out the content within the tag, in a beginner's level?

Thanks

Upvotes: 0

Views: 86

Answers (2)

Johan Park
Johan Park

Reputation: 11

Here you are

from bs4 import BeautifulSoup

navigator = BeautifulSoup(open("zory1.html"), "html.parser")

tds = navigator.find_all("td", {"width":"473"})

resultList = [item.strong.get_text() for item in tds]

for item in resultList:
    print item

Result

$ python test.py
Tytuł Filmu
1 - 5.05
KINO POWTÓREK: ZWIERZOGRÓD 

Upvotes: 0

alecxe
alecxe

Reputation: 473883

Use get_text() to get a node's text.

Complete working example where we go over all the rows and all the cells inside the table:

from bs4 import BeautifulSoup

data = """your HTML here"""
soup = BeautifulSoup(data, "html.parser")

for row in soup.find_all("tr"):
    print([cell.get_text(strip=True) for cell in row.find_all("td")])

Prints:

['Data', 'Tytuł Filmu', 'Godzina']
['', '1 - 5.05', '']
['1', 'KINO POWTÓREK: ZWIERZOGRÓDUSA/b.o\xa0 cena 10 zł', '16:30']

Upvotes: 1

Related Questions