我正在尝试使用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是否是正确的工具,或者我是否应该查看其他内容。
答案 0 :(得分:2)
.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 |