[英]Beautiful Soup element access
I am trying to use BeautifulSoup to extract information from a web page. 我正在尝试使用BeautifulSoup从网页中提取信息。 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. 我想提取每个
td
中的每个元素tr
元素。 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. 我想知道BeautifulSoup是否是正确的工具,或者我是否应该看看其他东西。
Each result in the .find_all()
list is another element object, so you can do further searches on these: .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))
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 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.