使用BS4解析HTML表

时间:2014-02-27 19:37:37

标签: python-2.7 html-parsing web-scraping beautifulsoup

我一直在尝试从这个站点(http://nflcombineresults.com/nflcombinedata.php?year=1999&pos=WR&college=)抓取数据的不同方法,但似乎无法让它们中的任何一个工作。我试过玩指数,但似乎无法使它工作。我想我此刻已经尝试了太多东西,所以如果有人能指出我正确的方向,我会非常感激。

我想提取所有信息并将其导出到.csv文件,但此时我只是想获取要打印的名称和位置以便开始使用。

这是我的代码:

import urllib2
from bs4 import BeautifulSoup
import re

url = ('http://nflcombineresults.com/nflcombinedata.php?year=1999&pos=&college=')

page = urllib2.urlopen(url).read()

soup = BeautifulSoup(page)
table = soup.find('table')

for row in table.findAll('tr')[0:]:
    col = row.findAll('tr')
    name = col[1].string
    position = col[3].string
    player = (name, position)
    print "|".join(player)

这是我得到的错误: 第14行,名称= col [1] .string IndexError:列表索引超出范围。

- UPDATE -

好的,我已经取得了一些进展。它现在允许我从头到尾,但它需要知道表中有多少行。我怎么能直到最后才通过它们? 更新的代码:

import urllib2
from bs4 import BeautifulSoup
import re

url = ('http://nflcombineresults.com/nflcombinedata.php?year=1999&pos=&college=')

page = urllib2.urlopen(url).read()

soup = BeautifulSoup(page)
table = soup.find('table')


for row in table.findAll('tr')[1:250]:
    col = row.findAll('td')
    name = col[1].getText()
    position = col[3].getText()
    player = (name, position)
    print "|".join(player)

2 个答案:

答案 0 :(得分:9)

我在8个小时左右后就知道了。学习很有趣。谢谢Kevin的帮助! 它现在包含将已删除数据输出到csv文件的代码。接下来是获取该数据并过滤掉某些位置......

这是我的代码:

import urllib2
from bs4 import BeautifulSoup
import csv

url = ('http://nflcombineresults.com/nflcombinedata.php?year=2000&pos=&college=')

page = urllib2.urlopen(url).read()

soup = BeautifulSoup(page)
table = soup.find('table')

f = csv.writer(open("2000scrape.csv", "w"))
f.writerow(["Name", "Position", "Height", "Weight", "40-yd", "Bench", "Vertical", "Broad", "Shuttle", "3-Cone"])
# variable to check length of rows
x = (len(table.findAll('tr')) - 1)
# set to run through x
for row in table.findAll('tr')[1:x]:
    col = row.findAll('td')
    name = col[1].getText()
    position = col[3].getText()
    height = col[4].getText()
    weight = col[5].getText()
    forty = col[7].getText()
    bench = col[8].getText()
    vertical = col[9].getText()
    broad = col[10].getText()
    shuttle = col[11].getText()
    threecone = col[12].getText()
    player = (name, position, height, weight, forty, bench, vertical, broad, shuttle, threecone, )
    f.writerow(player)

答案 1 :(得分:1)

由于防火墙权限,我无法运行您的脚本,但我相信问题出现在这一行:

col = row.findAll('tr')

rowtr标记,您要求BeautifulSoup查找该tr标记内的所有tr标记。你可能打算这样做:

col = row.findAll('td')

此外,由于实际文本不是直接位于tds内部,而是隐藏在嵌套diva中,因此使用getText方法可能会很有用.string

name = col[1].getText()
position = col[3].getText()