テーブルをこのようにするにはどうすればいいですか?batting gamelogs table - PythonとBeautifulSoupを使用するCSVファイルには?HTMLテーブルをCSVファイルに変換する
Rk、Gcar、Gtmなどと言う最初のヘッダーが必要で、テーブル内の他のヘッダー(季節の各月のヘッダー)は必要ありません。ここで
は私が持っているコードは、これまでです:
from bs4 import BeautifulSoup
from urllib2 import urlopen
import csv
def stir_the_soup():
player_links = open('player_links.txt', 'r')
player_ID_nums = open('player_ID_nums.txt', 'r')
id_nums = [x.rstrip('\n') for x in player_ID_nums]
idx = 0
for url in player_links:
print url
soup = BeautifulSoup(urlopen(url), "lxml")
p_type = ""
if url[-12] == 'p':
p_type = "pitching"
elif url[-12] == 'b':
p_type = "batting"
table = soup.find(lambda tag: tag.name=='table' and tag.has_attr('id') and tag['id']== (p_type + "_gamelogs"))
header = [[val.text.encode('utf8') for val in table.find_all('thead')]]
rows = []
for row in table.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('th')])
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
with open("%s.csv" % id_nums[idx], 'wb') as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(row for row in rows if row)
idx += 1
player_links.close()
if __name__ == "__main__":
stir_the_soup()
id_numsリストは別々のCSVファイルの名前として使用するために、各プレイヤーのID番号のすべてが含まれています。
各行について、一番左側のセルはタグであり、残りの行はタグです。ヘッダーに加えて、それをどのように1行に入れるのですか?
パンダにはおそらくあなたが望む線に沿っている素晴らしい機能 'read_html'があります。 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html – dashiell