from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("https://en.wikipedia.org/wiki/The_Walt_Disney_Company#Revenues")
soup = BeautifulSoup(html)
t = open("scrape_project.txt", "w")
table = soup.find('table', {"class": "wikitable"})
# get all rows, skipping first empty
data = table.select("tr")[1:]
# year data is in the scope attribute
years = [td.select("th[scope]")[0].text[:4] for td in data]
# Walt Disney Parks and Resort is the third element in each row
rec = [td.select("td")[2].text for td in data]
from pprint import pprint as pp
pp(years)
pp(rec)
:
['1991',
'1992',
'1993',
'1994',
'1995',
'1996',
'1997',
'1998',
'1999',
'2000',
'2001',
'2002',
'2003',
'2004',
'2005',
'2006',
'2007',
'2008',
'2009',
'2010',
'2011',
'2012',
'2013',
'2014']
['2,794.0',
'3,306',
'3,440.7',
'3,463.6',
'3,959.8',
'4,142[Rev 3]',
'5,014',
'5,532',
'6,106',
'6,803',
'6,009',
'6,691',
'6,412',
'7,750',
'9,023',
'9,925',
'10,626',
'11,504',
'10,667',
'10,761',
'11,797',
'12,920',
'14,087',
'15,099']
私はあなたが情報を保持したいならば、スライスしていない、text[:4]
とオフのリビジョンをスライスしました。
import re
m = re.compile("\d+,\d+")
rec = [m.search(td.select("td")[2].text).group() for td in data]
はあなたを与えるだろう:
['2,794',
'3,306',
'3,440',
'3,463',
'3,959',
'4,142',
'5,014',
'5,532',
'6,106',
'6,803',
'6,009',
'6,691',
'6,412',
'7,750',
'9,023',
'9,925',
'10,626',
'11,504',
'10,667',
'10,761',
'11,797',
'12,920',
'14,087',
'15,099']
あなたも
'4,142[Rev 3]'
から改訂3を削除すなわちお金から削除したい場合は、正規表現を使用することができます