出于某种原因,我的代码将返回值标签(例如,“到期日期”、“已记录”、“需要工作”等)。但是它不返回值。例如,当我运行代码时,它将返回"Due Date“,而不是"2014-Nov-27”。
更奇怪的是,如果我调整代码以接受url的原始输入,代码将返回所有内容(即标签和值)。
请记住,我正在尝试遍历具有相同HTML格式的urls列表。
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发布于 2017-05-09 01:44:52
最有可能的罪魁祸首是tbody。这是usually generated by browsers的“特殊”标签之一。而且,由于您使用requests获取页面源代码-没有涉及真正的浏览器,所以您不会在html_content中获取tbody。
而且,如果从您的超文本标记语言解析逻辑中消除tbody无济于事,那么可以尝试使用other parsers - html.parser或lxml代替html5lib。
https://stackoverflow.com/questions/43853502
复制相似问题