【发布时间】:2011-06-15 09:19:01
【问题描述】:
##### 更新 ###### :renderContents() 而不是 contents[0] 成功了。如果有人可以提供更好、更优雅的解决方案,我仍然会保持开放!
我正在尝试解析一些网页以获得所需的数据。该表没有类/ID 标记。所以我必须在 tr 内容中搜索“网站”。
手头的问题: 显示 td.contents 仅适用于文本而不是超链接,出于某种原因?我究竟做错了什么?有没有更好的方法在 Python 中使用 bs 来做到这一点?
那些建议 lxml 的人,我有一个正在进行的线程 herecentOS 和没有管理员权限的 lxml 安装在这个时候被证明是少数。因此探索 BeautifulSoup 选项。
HTML 示例:
<table border="2" width="100%">
<tbody><tr>
<td width="33%" class="BoldTD">Website</td>
<td width="33%" class="BoldTD">Last Visited</td>
<td width="34%" class="BoldTD">Last Loaded</td>
</tr>
<tr>
<td width="33%">
<a href="http://google.com"></a>
</td>
<td width="33%">01/14/2011
</td>
<td width="34%">
</td>
</tr>
<tr>
<td width="33%">
stackoverflow.com
</td>
<td width="33%">01/10/2011
</td>
<td width="34%">
</td>
</tr>
<tr>
<td width="33%">
<a href="http://stackoverflow.com"></a>
</td>
<td width="33%">01/10/2011
</td>
<td width="34%">
</td>
</tr>
</tbody></table>
到目前为止的 Python 代码:
f1 = open(PATH + "/" + FILE)
pageSource = f1.read()
f1.close()
soup = BeautifulSoup(pageSource)
alltables = soup.findAll( "table", {"border":"2", "width":"100%"} )
print "Number of tables found : " , len(alltables)
for table in alltables:
rows = table.findAll('tr')
for tr in rows:
cols = tr.findAll('td')
for td in cols:
print td.contents[0]
【问题讨论】:
-
应该
<a href="http://google.com"</a>是<a href="http://google.com"></a>(即是否缺少>?) -
更新了缺少>的HTML,还是不行。
标签: python beautifulsoup html-table html-parsing