Skip to main content
 首页 » 编程设计

python之BeautifulSoup 没有正确读取文档

2025年05月04日14wuhuacong

我正在尝试抓取 NBA 球员的统计数据,目的是对他们进行一些机器学习,我发现这些“可打印的球员文件”包含大量统计数据,非常简洁。不幸的是,我正在尝试使用 BeautifulSoup 来解析 html,但它根本不起作用。例如:

from bs4 import BeautifulSoup 
import codecs 
import urllib2 
 
url = 'http://www.nba.com/playerfile/ray_allen/printable_player_files.html' 
html = urllib2.urlopen(url).read() 
soup = BeautifulSoup(html) 
 
with open('ray_allen.txt', 'w') as f: 
    f.write(soup.prettify()) 
    f.close() 

给我一​​个看起来像这样的文件:

<html> 
 <head> 
  <!--no description was found--> 
  <!--no title was found--> 
  <!--no keywords found--> 
  <!--not article--> 
  <script> 
   var site = "nba"; 
var page = "player"; 
  </script> 
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> 
  <script language="Javascript"> 
   &lt;!-- 
var flashinstalled = 0; 
var flashversion = 0; 
MSDetect = "false"; 
if (navigator.plugins &amp;&amp; navigator.plugins.length) { 
    x = navigator.plugins["Shockwave Flash"]; 
    if (x) { 
        flashinstalle   d       =       2   ;    
 
           i   f       (   x   .   d   e   s   c   r   i   p   t   i   o   n   )       {    
 
               y       =       x   .   d   e   s   c   r   i   p   t   i   o   n   ;    
 
               f   l   a   s   h   v   e   r   s   i   o   n       =       y   .   c   h   a   r   A   t   (   y   .   i   n   d   e   x   O   f   (   '   .   '   )   -   1   )   ;    
 
           }    
 
       }       e   l   s   e    
 
           f   l   a   s   h   i   n   s   t   a   l   l   e   d       =       1   ;    
 
       i   f       (   n   a   v   i   g   a   t   o   r   .   p   l   u   g   i   n   s   [   "   S   h   o   c   k   w   a   v   e       F   l   a   s   h       2   .   0   "   ]   )       {    
 
           f   l   a   s   h   i   n   s   t   a   l   l   e   d       =       2   ;    
 
           f   l   a   s   h   v   e   r   s   i   o   n       =       2   ;    
 
       }    
[...] 

然后在结束之前继续另外 3000 多行([...] 是我添加的):

[...] 
   &lt;   /   b   o   d   y   &gt;    
 
   &lt;   /   h   t   m   l   &gt; 
  </script> 
 </head> 
</html> 

我也尝试了“http://www.basketball-reference.com/players/a/allenra02.html”,但那个给了我这个错误:

Traceback (most recent call last): File "test.py", line 9, in f.write(soup.prettify()) UnicodeEncodeError: 'ascii' codec can't encode character u'\xb7' in position 6167: ordinal not in range(128)

也许我应该使用其他东西来解析 html?还是其中一个问题很容易解决?我在这里读到的内容似乎表明使用 BeautifulSoup 应该让事情变得简单而不是困难!

编辑:行:

print soup.prettify() 

适用于终端的第二页,因此当它尝试写入文件时发生了一些事情——这不是 BeautifulSoup 的问题

请您参考如下方法:

这表现出与 bug 972466 相同的症状,已在 4.0.3 中修复。我建议升级到最新版本的 Beautiful Soup 4。