【发布时间】:2014-12-02 10:03:48
【问题描述】:
我对 Python 还很陌生,我已经编写了一个刮板,它可以按照我需要的确切方式打印我刮掉的数据,但是我在将数据写入文件时遇到了麻烦。我需要它看起来与在 IDLE 中打印时完全相同的方式和顺序
import requests
import re
from bs4 import BeautifulSoup
year_entry = raw_input("Enter year: ")
week_entry = raw_input("Enter week number: ")
week_link = requests.get("http://sports.yahoo.com/nfl/scoreboard/?week=" + week_entry + "&phase=2&season=" + year_entry)
page_content = BeautifulSoup(week_link.content)
a_links = page_content.find_all('tr', {'class': 'game link'})
for link in a_links:
r = 'http://www.sports.yahoo.com' + str(link.attrs['data-url'])
r_get = requests.get(r)
soup = BeautifulSoup(r_get.content)
stats = soup.find_all("td", {'class':'stat-value'})
teams = soup.find_all("th", {'class':'stat-value'})
scores = soup.find_all('dd', {"class": 'score'})
try:
game_score = scores[-1]
game_score = game_score.text
x = game_score.split(" ")
away_score = x[1]
home_score = x[4]
home_team = teams[1]
away_team = teams[0]
away_team_stats = stats[0::2]
home_team_stats = stats[1::2]
print away_team.text + ',' + away_score + ',',
for stats in away_team_stats:
print stats.text + ',',
print '\n'
print home_team.text + ',' + home_score +',',
for stats in home_team_stats:
print stats.text + ',',
print '\n'
except:
pass
我完全不知道如何让它打印到 txt 文件,就像在 IDLE 中打印一样。该代码仅在 NFL 赛季结束的几周内运行。因此,如果您测试代码,我建议 year = 2014 和 week = 12(或之前)
谢谢,
JT
【问题讨论】:
标签: python beautifulsoup python-requests