簡體   English   中英

美麗的湯元素訪問

[英]Beautiful Soup element access

我正在嘗試使用BeautifulSoup從網頁中提取信息。 我的代碼在這里:

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

產量

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

我想提取每個td中的每個元素tr元素。 就像是

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

在得到我想要的文檔的一部分后,我不確定如何查看子標簽。

我想知道BeautifulSoup是否是正確的工具,或者我是否應該看看其他東西。

.find_all()列表中的每個結果都是另一個元素對象,因此您可以對這些進行進一步搜索:

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

這給了我:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM