简体   繁体   中英

Beautiful Soup element access

I am trying to use BeautifulSoup to extract information from a web page. My code is here:

from bs4 import BeautifulSoup
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
infile = opener.open('http://en.wikipedia.org/wiki/American_films_of_1971')
page = infile.read()
soup = BeautifulSoup(page)
soup.prettify().encode('utf8')
print (soup.find_all("table", "wikitable"))

output

[<table class="wikitable">
<tr>
<th style="width:25%;">Title</th>
<th style="width:20%;">Director</th>
<th style="width:30%;">Cast</th>
<th style="width:10%;">Genre/Note</th>
<th style="width:3%;">
<p><br/></p>
</th>
</tr>
<tr>
<td><i><a class="mw-redirect" href="/wiki/$" title="$">$</a> aka Dollars</i></td>
<td><a href="/wiki/Richard_Brooks" title="Richard Brooks">Richard Brooks</a></td>
<td><a href="/wiki/Warren_Beatty" title="Warren Beatty">Warren Beatty</a>, <a href="/wiki/Goldie_Hawn" title="Goldie Hawn">Goldie Hawn</a></td>
<td><a href="/wiki/Comedy" title="Comedy">Comedy</a>, <a href="/wiki/Crime" title="Crime">Crime</a></td>
<td></td>
</tr>
<tr>
<td><i><a href="/wiki/200_Motels" title="200 Motels">200 Motels</a></i></td>
<td><a href="/wiki/Tony_Palmer" title="Tony Palmer">Tony Palmer</a>, Charles Swenson</td>
<td><a href="/wiki/Frank_Zappa" title="Frank Zappa">Frank Zappa</a>, <a href="/wiki/Ringo_Starr" title="Ringo Starr">Ringo Starr</a>, <a href="/wiki/Theodore_Bikel" title="Theodore Bikel">Theodore Bikel</a></td>
<td><a href="/wiki/Comedy" title="Comedy">Comedy</a>, <a href="/wiki/Musical_film" title="Musical film">Musical</a></td>
<td></td>
</tr>
</table>]

I want to extract each td element in each tr element. Something like

aka Dollars | Richard Brooks | Warren Beatty | Crime
200 Models | Tony Palmer, Charles Swenson | Frank Zappa | Comedy

I am unsure how to look into the child tags after I get the part of the document I want.

I was wondering if BeautifulSoup is the right tool or if I should look at something else.

Each result in the .find_all() list is another element object, so you can do further searches on these:

for table in soup.find_all("table", "wikitable"):
    for row in table.find_all('tr'):
        cells = []
        for cell in row.find_all('td'):
            cells.append(cell.get_text())
        print(' | '.join(cells))

This gives me:

$ aka Dollars | Richard Brooks | Warren Beatty, Goldie Hawn | Comedy, Crime | 
200 Motels | Tony Palmer, Charles Swenson | Frank Zappa, Ringo Starr, Theodore Bikel | Comedy, Musical | 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM