在主页,旅游统计数据似乎正在由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中去掉逗号。
如果您的问题已被解答,请点击接受。 – smci