我試圖循環遍歷表格行並打印某些td。我可以單獨打印每個文件,但我不確定如何同時打印同一行上的兩個td。我想知道的是我在何處放置for循環和打印標籤以使其工作。Python:Beautifulsoup - 解析表格
<div id="main">
<table>
<tbody>
<tr>
<td><span class="bold">answer</span> </td>
<td></td>
<td>
<option value="1|0|%" selected="selected">%</option>
<option value="100|0|fraction">fraction</option>
<option value="100|0|ratio">ratio</option>
</td>
</tr>
</tbody>
</table>
</div>
我試圖做到這一點是
def summary(url, i):
html = wget(url)
soup = BeautifulSoup(html)
for row in soup.findAll('div', {'id': 'main'}):
for ops in row.findAll('tr'):
for tds1 in ops.findAll('td'):
for opt in tds1.findAll('option', {'selected': 'selected'}):
return opt
for ops in row.findAll('tr'):
for tds1 in ops.findAll('td'):
for spans in tds1.findAll('span', {'class': 'bold'}):
return spans
print (i, opt, spans)
您正在分析的HTML和預期的輸出將有助於更正代碼 – shaktimaan 2014-08-29 00:41:03
您確定在代碼中有'return opt'嗎?這意味着這個代碼從不打印任何東西。它也看起來像縮進問題:你確定以'湯'開始的行是縮進? – 2014-08-29 00:41:09
另外,你是什麼意思「同時在同一行打印兩個」? – 2014-08-29 00:41:38