据我所知,我各有两台机器,运行 python 2.5 和 BeautifulSoup 3.1.0.1。
我正在尝试抓取http://utahcritseries.com/RawResults.aspx ,使用:
from BeautifulSoup import BeautifulSoup
import urllib2
base_url = "http://www.utahcritseries.com/RawResults.aspx"
data=urllib2.urlopen(base_url)
soup=BeautifulSoup(data)
i = 0
table=soup.find("table",id='ctl00_ContentPlaceHolder1_gridEvents')
#table=soup.table
print "begin table"
for row in table.findAll('tr')[1:10]:
i=i + 1
col = row.findAll('td')
date = col[0].string
event = col[1].a.string
confirmed = col[2].string
print '%s - %s' % (date, event)
print "end table"
print "%s rows processed" % i
在我的 Windows 计算机上,我得到了正确的结果,它是日期和事件名称的列表。在我的 Mac 上,我没有。相反,我得到
3/2/2002 - Rocky Mtn Raceway Criterium
None - Rocky Mtn Raceway Criterium
3/23/2002 - Rocky Mtn Raceway Criterium
None - Rocky Mtn Raceway Criterium
4/2/2002 - Rocky Mtn Raceway Criterium
None - Saltair Time Trial
4/9/2002 - Rocky Mtn Raceway Criterium
None - DMV Criterium
4/16/2002 - Rocky Mtn Raceway Criterium
我注意到的是,当我
print row
在我的 Windows 机器上,tr 数据看起来与源 html 完全相同。请注意第二个表格行上的样式标签。这是前两行:
<tr>
<td>
3/2/2002
</td>
<td>
<a href="Event.aspx?id=226">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=226">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
<tr style="color:#333333;background-color:#EFEFEF;">
<td>
3/16/2002
</td>
<td>
<a href="Event.aspx?id=227">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=227">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
在我的 Mac 上,当我打印前两行时,样式信息将从 tr 标记中删除,并移至每个 td 字段中。我不明白为什么会发生这种情况。对于每个其他日期值,我都没有得到任何值,因为 BeautifulSoup 在每隔一个日期周围放置一个字体标签。这是 mac 的输出:
<tr>
<td>
3/2/2002
</td>
<td>
<a href="Event.aspx?id=226">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=226">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
<tr bgcolor="#EFEFEF">
<td>
<font color="#333333">
3/16/2002
</font>
</td>
<td>
<font color="#333333">
<a href="Event.aspx?id=227">
Rocky Mtn Raceway Criterium
</a>
</font>
</td>
<td>
<font color="#333333">
Confirmed
</font>
</td>
<td>
<font color="#333333">
<a href="Event.aspx?id=227">
Points
</a>
</font>
</td>
<td>
<font color="#333333">
<a disabled="disabled">
Results
</a>
</font>
</td>
</tr>
我的脚本在 Windows 下显示正确的结果 - 我需要做什么才能让我的 Mac 正常工作?
最佳答案
有documented problems使用 BeautifulSoup 3.1 版本。
您可能需要仔细检查您实际使用的版本,如果是,则降级。
关于python-beautifulsoup 误报了我的 html 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/810173/