使用BS4解析HTML表

ISu*_*ife 4 beautifulsoup html-parsing web-scraping python-2.7

我一直在尝试从这个站点抓取数据的不同方法(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)
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:第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)
Run Code Online (Sandbox Code Playgroud)

ISu*_*ife 10

我只用了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)
Run Code Online (Sandbox Code Playgroud)