python - 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(";")
此外,一些用“。”分隔的数字。正在自动转换为日期。
有什么想法可以解决这些问题吗?
解决方案
我对您的脚本进行了一些更改。为了构建 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 时,您可以选择用于数据的列类型。查看本指南。
推荐阅读
- mysql - Mysql int 数据类型的空默认值
- autocomplete - Atom自动完成加导航,不起作用
- python - 我想在 django 社交应用登录后添加服装字段
- java - 如何在 Java 8 中检查两个未排序的列表是否相等?
- c++ - 链表显示功能不正常
- node.js - 在发送 8 个字节之前,Chrome 不会将文件显示为正在下载(Firefox 会)
- node.js - 在 Centos 7 上安装 nest.js
- java - 使用斯坦福 CoreNLP 构建知识图谱
- java - 用户登录系统后,从会话中捕获登录用户的名称
- sql - 如何在 Oracle SQL 中获得过去三天每天的滚动不同计数?