【问题标题】:Data I'm trying to scrape cut short我试图缩短的数据
【发布时间】:2015-07-15 20:55:12
【问题描述】:

我正在尝试使用 Python 将这个 basketball-reference example 中的播放表抓取到一个 CSV 文件中。

当我运行此代码时,表格被缩短,许多单元格丢失。我是一名编程 n00b,如有任何帮助,我们将不胜感激。

from bs4 import BeautifulSoup
from urllib2 import urlopen
import csv

bref = "http://www.basketball-reference.com"
print "Enter game code:"
game = raw_input("> ")

def make_soup(url):
    return BeautifulSoup(urlopen(url), "lxml")

def get_pbp(pbp):
    soup = make_soup(bref + "/boxscores/pbp/" + game + ".html")
    table = soup.find("table", "no_highlight stats_table")
    rows = [row.find_all("td") for row in table.find_all("tr")]

    data = []
    for row in rows:
        values = []
        for value in row:
            if value.string is None:
                values.append(u"")
            else:
                values.append(value.string.replace(u"\xa0", u""))
        data.append(values)
    return data

if __name__ == '__main__':

    print "Writing data for game " + game

    with open(game + '.csv', 'w') as f:
        writer = csv.writer(f)
        writer.writerows(get_pbp(game))

    print game + " has been successfully scraped."

【问题讨论】:

    标签: python html web-scraping screen-scraping


    【解决方案1】:

    您需要跳过空白单元格

    table = soup.find("table", class_="no_highlight stats_table")
    rows = [[cell.text.replace(u"\xa0", u"").strip() for cell in row.find_all("td") if cell.text.strip()]
            for row in table.find_all("tr")[2:]]
    
    with open(game + '.csv', 'w') as f:
        writer = csv.writer(f)
        writer.writerows(rows)
    

    【讨论】:

    猜你喜欢
    • 2013-03-11
    • 2015-08-15
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多