首页 > 解决方案 > HTML Scraping with Beautiful Soup - 不需要的换行符

问题描述

我一直在尝试编写一个脚本来从 html 页面获取数据并将其保存到 .csv 文件。但是我遇到了 3 个小问题。

首先,当保存到 .csv 时,我会得到一些不需要的换行符,这些换行符会弄乱输出文件。

其次,球员姓名(数据涉及NBA球员)出现两次。

from bs4 import BeautifulSoup
import requests
import time


teams = ['atlanta-hawks', 'boston-celtics', 'brooklyn-nets']

seasons = []
a=2018
while (a>2016):
    seasons.append(str(a))
    a-=1
print(seasons)  
for season in seasons:

    for team in teams:
        my_url = ' https://www.spotrac.com/nba/'+team+'/cap/'+ season +'/'

        headers = {"User-Agent" : "Mozilla/5.0"}

        response = requests.get(my_url)
        response.content

        soup = BeautifulSoup(response.content, 'html.parser')

        stat_table = soup.find_all('table', class_ = 'datatable')


        my_table = stat_table[0]

        plik = team + season + '.csv'   
        with open (plik, 'w') as r:
            for row in my_table.find_all('tr'):
                for cell in row.find_all('th'):
                    r.write(cell.text)
                    r.write(";")

            for row in my_table.find_all('tr'):
                for cell in row.find_all('td'): 
                    r.write(cell.text)
                    r.write(";")

此外,一些用“。”分隔的数字。正在自动转换为日期。

有什么想法可以解决这些问题吗?

输出文件截图

标签: pythonweb-scrapingbeautifulsoup

解决方案


我对您的脚本进行了一些更改。为了构建 URL,我使用字符串插值(而不是串联)。为了摆脱多余的空格,我使用了strip()在字符串上定义的方法。当涉及到名称重复时,我选择了<a>标签,然后调用.text了 BeautifulSoup 选择器。

# pip install beautifulsoup4
# pip install requests

from bs4 import BeautifulSoup
import requests
import time

teams = ['atlanta-hawks', 'boston-celtics', 'brooklyn-nets']
seasons = [2018, 2017]

for season in seasons:
    for team in teams:
        my_url = f'https://www.spotrac.com/nba/{team}/cap/{season}/'
        headers = {"User-Agent": "Mozilla/5.0"}

        response = requests.get(my_url)
        response.content

        soup = BeautifulSoup(response.content, 'html.parser')
        stat_table = soup.find_all('table', class_ = 'datatable')
        my_table = stat_table[0]

        csv_file = f'{team}-{season}.csv'
        with open(csv_file, 'w') as r:
            for row in my_table.find_all('tr'):
                for cell in row.find_all('th'):
                    r.write(cell.text.strip())
                    r.write(";")

                for i, cell in enumerate(row.find_all('td')):
                    if i == 0:
                        r.write(cell.a.text.strip())
                    else:
                        r.write(cell.text.strip())
                    r.write(";")
                r.write("\n")

当谈到 Excel 将数字转换1.31为日期时,Excel 试图变得聪明,但失败了。我认为当您导入 CSV 时,您可以选择用于数据的列类型。查看本指南


推荐阅读