刮掉表和所需数据有什么不对?

时间:2012-12-05 18:29:27

标签: python-2.7 web-scraping beautifulsoup

我试图在http://www.scoresandodds.com/grid_20111225.html的桌子上搜索迈阿密热火及其对手的数据。我遇到的问题是,NBA和NFL以及其他体育项目的表都是明确标记的,我得到的所有数据都来自NFL表。另一个问题是我想整个赛季的数据和不同表格的数量变化以及迈阿密的位置变化。这是我到目前为止用于不同表格的代码;

那为什么不能完成这项工作呢?感谢你的耐心;我是一个真正的乞丐,而且我已经试图解决这个问题好几天了,没有效果。

def tableSnO(htmlSnO):
gameSections = soup.findAll('div', 'gameSection')
for gameSection in gameSections:
    header = gameSection.find('div', 'header')
    if header.get('id') == 'nba':
        rows = gameSections.findAll('tr')
        def parse_string(el):
            text = ''.join(el.findAll(text=True))
            return text.strip()
        for row in rows:
            data = map(parse_string, row.findAll('td'))
            return data  

最近我决定尝试不同的方法;如果我刮掉整个页面并得到有问题的数据的索引(这是它停止的地方:)我可以从列表中获取下一组数据,因为表的结构永远不会改变。我也可以像获得htmlSnO一样获得对手的球队名称。感觉就像这是基本的东西而且它让我感到害怕,我无法做到这一点。

def tableSnO(htmlSnO):
oddslist = soupSnO.find('table', {"width" : "100%", "cellspacing" : "0", "cellpadding" : "0"})
rows = oddslist.findAll('tr',)
def parse_string(el):
    text = ''.join(el.findAll(text=True))
    return text.strip()
for row in rows:
    data = map(parse_string, row.findAll('td'))

    for teamName in data:
        if re.match("(.*)MIAMI HEAT(.*)", teamName):
            return teamName
            return data.index(teamName)  

1 个答案:

答案 0 :(得分:0)

使用工作代码的新的和最终的答案:

您想要的页面部分包含:

<div class="gameSection">
    <div class="header" id="nba">

这可以让你进入NBA桌面:

def tableSnO(htmlSnO):
    gameSections = soup.findAll('div', 'gameSection')
    for gameSection in gameSections:
        header = gameSection.find('div', 'header')
        if header.get('id') == 'nba':
            # process this gameSection
            print gameSection.prettify()

作为一个完整的例子,这是我用来测试的完整代码:

import sys
import urllib2
from bs4 import BeautifulSoup

f = urllib2.urlopen('http://www.scoresandodds.com/grid_20111225.html')
html = f.read()
soup = BeautifulSoup(html)

gameSections = soup.findAll('div', 'gameSection')
for gameSection in gameSections:
    header = gameSection.find('div', 'header')
    if header.get('id') == 'nba':
        table = gameSection.find('table', 'data')
        print table.prettify()

打印NBA数据表。