【发布时间】:2017-10-06 19:14:28
【问题描述】:
出于某种原因,我的代码将返回值标签(例如,“截止日期”、“记录”、“需要工作”等),但它不返回值。例如,当我运行代码时,它会返回“到期日期”而不是“2014-Nov-27”。
更奇怪的是,如果我调整代码以接受 url 的原始输入,代码会返回所有内容(即标签和值)。
请记住,我正在尝试遍历具有相同 HTML 格式的 url 列表。
HTML
table id="mcs-initial-abstract-grid" >
<tr class="mci-grid-row-header">
<th >
<table style="width:100%">
<tr>
<td>SOME STRING</td>
<td>SOME INTEGER </td>
<td>SOME STRING</td>
</tr>
</table>
</th>
</tr>
<tr>
<td>
<table style="width:100%">
<tr class="mci-gridview-alternate">
<td style="width:25%"><strong>Due Date:</strong></td>
<td style="width:20%">2014-Nov-27</td>
<td style="width:20%"><strong>Recorded:</strong></td>
<td style="width:35%">2015-Nov-7</td>
</tr>
<tr >
<td><strong>Work Required:</strong></td>
<td>$20</td>
<td><strong>Variable:</strong></td>
<td>2015-Nov-25 14:20</td>
</tr>
</table>
</td>
</tr>
<tr>
我的代码:
from bs4 import BeautifulSoup as bs
import requests
import urllib
url = 'enter url here'
r = requests.get(url)
html_content = r.text
soup = bs(html_content, 'html5lib')
for tags in soup.find_all('table', id='mcs-initial-abstract-grid'):
for tbody in tags.find_all('tbody'):
for tr in tbody.find_all('tr', {'class':'mci-gridview-alternate'} ):
for td in tr.find_all('td'):
print td.text
【问题讨论】:
-
也许
html5lib慷慨地提供了缺失的标签;但是,我注意到问题列出的 HTML 中缺少tbody。
标签: python web-scraping beautifulsoup html-table