将网页抓取导出到csv文件

时间:2019-10-19 15:23:32

标签: python html web-scraping export-to-csv

import csv
import requests
from bs4 import BeautifulSoup

page = requests.get("https://www.cbssports.com/nba/stats/playersort/nba/year-2019-season-preseason-category-scoringpergame")
soup = BeautifulSoup(page.content, 'html.parser')

for record in soup.find_all('tr'):
    try:
        print(record.contents[0].text)
        print(record.contents[6].text)
        print(record.contents[7].text)
        print(record.contents[8].text)
        print(record.contents[9].text)
        print(record.contents[10].text)
        print(record.contents[12].text)
        print(record.contents[13].text)
        print(record.contents[14].text)
        print(record.contents[15].text)
    except:
        pass
    print('\n')

def scrape_data(url):

    response = requests.get("https://www.cbssports.com/nba/stats/playersort/nba/year-2019-season-preseason-category-scoringpergame", timeout=10)
    soup = BeautifulSoup(response.content, 'html.parser')

    table = soup.find_all('table')[1]

    rows = table.select('tbody > tr')

    header = [th.text.rstrip() for th in rows[1].find_all('th')]

    with open('statsoutput.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(header)
        for row in rows[1:]:
            data = [th.text.rstrip() for th in row.find_all('td')]
            writer.writerow(data)


if __name__=="__main__":
    url = "https://www.cbssports.com/nba/stats/playersort/nba/year-2019-season-preseason-category-scoringpergame"
    scrape_data(url)

iv一直试图将统计信息从该网页导出到csv file。 当我运行我的代码时,第一部分工作正常并检索我想要的数据。 但是该函数无法将其导出到csv file中,并且出现此错误:

table = soup.find_all('table')[1]
IndexError: list index out of range

我不确定为什么。

1 个答案:

答案 0 :(得分:3)

您收到此错误,因为此站点只有一个<table /> html元素。因此,soupe.find_all()返回的列表的长度为1。您可以通过执行soupe.find_all('table')[0]或以干净的方式soup.table来解决此错误。

我还检查并测试了您的代码,并建议这样做:

table = soup.table
rows = table.find_all('tr')

这些更改后,一切都会正常运行。您可以检查运行here的代码。希望对您有所帮助。