爲什麼我只能從PLAYER_NAME中的最後一名玩家那裏獲得統計信息?在Python腳本中循環,僅獲得最後結果
我想從PLAYER_NAME的所有玩家獲得統計數據。
import csv
import requests
from bs4 import BeautifulSoup
import urllib
PLAYER_NAME = ["andy-murray/mc10", "rafael-nadal/n409"]
URL_PATTERN = 'http://www.atpworldtour.com/en/players/{}/player-stats?year=0&surfaceType=clay'
for item in zip (PLAYER_NAME):
url = URL_PATTERN.format(item)
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html)
table = soup.find('div', attrs={'class': 'mega-table-wrapper'})
list_of_rows = []
for row in table.findAll('tr'):
list_of_cells = []
for cell in row.findAll('td'):
text = (cell.text.encode("utf-8").strip())
list_of_cells.append(text)
list_of_rows.append(list_of_cells)
outfile = open("./tennis.csv", "wb")
writer = csv.writer(outfile)
writer.writerow(["Name", "Stat"])
writer.writerows(list_of_rows)
你在每次迭代過'PLAYER_NAME'再造'list_of_rows'。 – CTKlein
我該如何解決這個問題? – Depekker
將list_of_rows定義移至循環的外部 – georgealton