【发布时间】:2015-05-20 20:42:58
【问题描述】:
我似乎无法找出正确的缩进/子句位置来让这个循环超过 1 页。此代码当前可以很好地打印出 CSV 文件,但只针对第一页。
#THIS WORKS BUT ONLY PRINTS THE FIRST PAGE
from bs4 import BeautifulSoup
from urllib2 import urlopen
import csv
page_num = 1
total_pages = 20
with open("MegaMillions.tsv","w") as f:
fieldnames = ['date', 'numbers', 'moneyball']
writer = csv.writer(f, delimiter = '\t')
writer.writerow(fieldnames)
while page_num < total_pages:
page_num = str(page_num)
soup = BeautifulSoup(urlopen('http://www.usamega.com/mega-millions-history.asp?p='+page_num).read())
for row in soup('table',{'bgcolor':'white'})[0].findAll('tr'):
tds = row('td')
if tds[1].a is not None:
date = tds[1].a.string.encode("utf-8")
if tds[3].b is not None:
uglynumber = tds[3].b.string.split()
betternumber = [int(uglynumber[i]) for i in range(len(uglynumber)) if i%2==0]
moneyball = tds[3].strong.string.encode("utf-8")
writer.writerow([date, betternumber, moneyball])
page_num = int(page_num)
page_num += 1
print 'We\'re done here.'
当然,这只会打印最后一页:
#THIS WORKS BUT ONLY PRINTS THE LAST PAGE
from bs4 import BeautifulSoup
from urllib2 import urlopen
import csv
page_num = 1
total_pages = 20
while page_num < total_pages:
page_num = str(page_num)
soup = BeautifulSoup(urlopen('http://www.usamega.com/mega-millions-history.asp?p='+page_num).read())
with open("MegaMillions.tsv","w") as f:
fieldnames = ['date', 'numbers', 'moneyball']
writer = csv.writer(f, delimiter = '\t')
writer.writerow(fieldnames)
for row in soup('table',{'bgcolor':'white'})[0].findAll('tr'):
tds = row('td')
if tds[1].a is not None:
date = tds[1].a.string.encode("utf-8")
if tds[3].b is not None:
uglynumber = tds[3].b.string.split()
betternumber = [int(uglynumber[i]) for i in range(len(uglynumber)) if i%2==0]
moneyball = tds[3].strong.string.encode("utf-8")
writer.writerow([date, betternumber, moneyball])
page_num = int(page_num)
page_num += 1
print 'We\'re done here.'
【问题讨论】:
-
将代码提取到函数中并单独排除故障,而不是大量代码。
标签: python csv beautifulsoup