2011-08-15 57 views
2

我想从该网站的表格中提取数据:http://www.pgatour.com/r/stats/info/xm.html?101 然后将其保存为.csv并将其带入iWorks Numbers表单。 我一直在尝试与Python,BeautifulSoup和机械化。通过查看其他例子,我一直在没有知识的情况下尝试,但没有成功。我已经走到这一步:如何使用Python提取网页数据,BeautiflSoup和从表格中机械化

from BeautifulSoup import BeautifulSoup, SoupStrainer 
from mechanize import Browser 
import re 
br = Browser() 
response = br.open("http://www.pgatour.com/r/stats/info/xm.html?101").read() 

然后我看与萤火虫的代码,我猜我需要解析的是<tbody></tbody>之间的数据。但我不知道该怎么做。 任何帮助非常感谢。

+0

如果您的问题已被解答,请点击接受。 – smci

回答

4

在主页,旅游统计数据似乎正在由JavaScript填充<div class="tourViewData"> ... populateDDs(); BS不解析JavaScript中,看到了许多其他的做题。作为一种解决方法,选择并保存该HTML选项作为本地HTML文件,作为解决方法。)

首先,将s设置为该URL的BeautifulSoup对象(我用斜纹不生机械化,在这里把你的机械化当量):

from BeautifulSoup import BeautifulSoup, SoupStrainer 
#from mechanize import Browser 
from twill.commands import * 
import re 

go("http://www.pgatour.com/r/stats/info/xm.html?101") 
s = BeautifulSoup(get_browser().get_html()) 

反正你要找的统计的表是标有<tbody><tr class="tourStatTournHead">表。 只是为了让事情有点古怪,其行中的标签属性交替定义为<tr class="tourStatTournCellAlt"<tr class=""...。 我们应该搜索第一个<tr class="tourStatTournCellAlt",然后在表中处理每个<tr>,除了标题行(<tr class="tourStatTournHead">)之外。

要通过行迭代:(它可能会或可能不会是分层的,如果它嵌入了Titleist品牌标志)

tbl = s.find('table', {'class':'tourStatTournTbl'}) 

def extract_text(ix,tg): 
    if ix==2: # player name field, may be hierarchical 
     tg = tg.findChildren()[0] if (len(tg.findChildren())>0) else tg 
    return tg.text.encode() 

for rec in tbl.findAll('tr'): # {'class':'tourStatTournCellAlt'}): 
    # Skip header rows 
    if (u'tourStatTournHead' in rec.attrs[0]): 
     continue   
    # Extract all fields 
    (rank_tw,rank_lw,player,rounds,avg,tot_dist,tot_drives) = \ 
     [extract_text(i,t) for (i,t) in enumerate(rec.findChildren(recursive=False))] 
    # ... do stuff 

我们增加一个辅助功能,供玩家名称 也许你想将大多数字段转换为除player(string)和avg(float)之外的int();如果是这样,请记住从等级字段中去除可选的'T'(用于绑定),并从tot_dist中去掉逗号。

+0

感谢您的努力和时间!试图输入你的代码我得到这个错误: – Mikael

+0

谢谢你的努力和时间!试图输入你的代码我得到这个错误:>>> tbl = s.find('table',{'class':'tourStatTournTbl'}) 回溯(最近呼叫最后): 文件“”,第1行,在 NameError:name's'没有定义 我猜你的代码很好,这是我做错了什么。我不想浪费你的时间了。我想我需要在尝试这个之前正确学习Python。我将复制你的代码并研究一些更多的python,稍后再尝试。非常感谢你!!! – Mikael

+0

s应该是该URL的BeautifulSoup对象。 (我用斜纹不机械化。) – smci