【发布时间】:2021-07-28 06:37:22
【问题描述】:
我对 python 和 webscraping 还很陌生,但是我设法得到了一个工作良好的表格来打印,我只是好奇如何将这个表格以与 print 语句完全相同的格式保存到 CSV 文件中。任何逻辑解释将不胜感激,非常有帮助!我的代码在下面...
from bs4 import BeautifulSoup
import requests
import time
htmlText = requests.get('https://www.fangraphs.com/teams/mariners/stats').text
soup = BeautifulSoup(htmlText, 'lxml', )
playerTable = soup.find('div', class_='team-stats-table')
def BattingStats():
headers = [th.text for th in playerTable.find_all("th")]
fmt_string = " ".join(["{:<25}", *["{:<6}"] * (len(headers) - 1)])
print(fmt_string.format(*headers))
for tr in playerTable.find_all("tr")[1:55]:
tds = [td.text for td in tr.select("td")]
with open('MarinersBattingStats.csv', 'w') as f:
f.write(fmt_string.format(*tds))
print(fmt_string.format(*tds))
if __name__ == 'main':
while True:
BattingStats()
timeWait = 100
time.sleep(432 * timeWait)
BattingStats()
【问题讨论】:
标签: python html web-scraping beautifulsoup