2016-11-24 95 views
1

無法正確處理大型桌面遊戲籃球數據時遇到問題。代碼:BeautifulSoup錯誤地解析表格

import urllib.request 
from bs4 import BeautifulSoup 

request = urllib.request.Request('http://www.basketball-reference.com/boxscores/pbp/201611220LAL.html') 
result = urllib.request.urlopen(request) 
resulttext = result.read() 
soup = BeautifulSoup(resulttext, "html.parser") 

pbpTable = soup.find('table', id="pbp") 

如果你自己運行這個例子,你會發現,該表不能完全解析後的所有我們得到了是這樣的:

<table class="suppress_all sortable stats_table" data-cols-to-freeze="1" id="pbp"> 
<caption>Play-By-Play Table</caption> 
<tr class="thead" id="q1"> 
<th colspan="6">1st Q</th></tr></table> 

問題本身打印解析湯變量給(除其他外)

</div> 
<div class="table_wrapper" id="all_pbp"> 
<div class="section_heading"> 
<span class="section_anchor" data-label="Play-By-Play" id="pbp_link"></span> 
<h2>Play-By-Play</h2> <div class="section_heading_text"> 
<ul> <li>  Jump to: <a href="#q1">1st</a> | <a href="#q2">2nd</a> | <a href="#q3">3rd</a> | <a href="#q4">4th</a> <br> <span class="bbr-play-score key">scoring play</span> <span class="bbr-play-tie key">tie</span> <span class="bbr-play-leadchange key">lead change</span></br></li> 
</ul> 
</div> 
</div> <div class="table_outer_container"> 
<div class="overthrow table_container" id="div_pbp"> 
<table class="suppress_all sortable stats_table" data-cols-to-freeze="1" id="pbp"><caption>Play-By-Play Table</caption><tr class="thead" id="q1"> 
<th colspan="6">1st Q</th></tr></table></div></div></div></div></div></body></html> 

最重要的是,一個/表標籤出現無處不在。查看相關鏈接的頁面源代碼,我們可以看到表格沒有關閉 - 它會持續一段時間。除了實現我自己的HTML解析代碼之外,是否還有其他解決方案?

回答

2

使用"lxml""html5lib"代替"html.parser"

soup = BeautifulSoup(resulttext, "lxml")` 

,你會得到更多的數據。

但是如果您還沒有安裝,您可能需要安裝lxmlhtml5lib

pip install lxml 

pip install html5lib 

lxml可能需要C/C++編譯器,libxml庫(libxml.dll在Windows上),等

+0

謝謝! html5lib爲我工作,而我遇到了「無法找到vcvarsall.bat」錯誤與lxml ...只是意識到你警告我有關額外的要求。我擅長閱讀! –

+0

BTW:請參閱[Python擴展包的非官方Windows二進制文件](http://www.lfd.uci.edu/~gohlke/pythonlibs/)。 Windows上有針對Python的預編譯模塊。有'lxml'。但它仍然可能需要'libxml.dll','libxstl.dll'。或檢查[Anaconda](https://www.continuum.io/downloads) - 它安裝Python和許多[預編譯模塊](https://docs.continuum.io/anaconda/pkg-docs) - 有lxml '也是。 – furas