웹에서 일부 테이블을 긁어서 csv에 저장하는 기능을 만들었지 만 왜 작동하지 않는지 알 수 없습니다. 다음은 웹을 긁을 때 값 오류 : 닫힌 파일에 대한 입출력 작업
내가 시도하는 코드입니다 :record("A/041/0.html")
이 출력은 다음과 같다 : 다음
import csv
import urllib2
from bs4 import BeautifulSoup
def record (part) :
url="http://www.admision.unmsm.edu.pe/res20130914/{}".format(part)
u=urllib2.urlopen(url)
try:
html=u.read()
finally:
u.close()
soup=BeautifulSoup(html)
c=[]
for n in soup.find_all('center'):
for b in n.find_all('a')[2:]:
c.append(b.text)
t=(len(c)-2)/2
with open('name.csv', 'wb') as f:
writer = csv.writer(f)
for i in range(t):
url = "http://www.admision.unmsm.edu.pe/res20130914/A/011/{}.html".format(i)
u = urllib2.urlopen(url)
try:
html = u.read()
finally:
u.close()
soup=BeautifulSoup(html)
for tr in soup.find_all('tr')[2:]:
tds = tr.find_all('td')
row = [elem.text.encode('utf-8') for elem in tds[:4]]
writer.writerow(row)
, 내 함수를 실행
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-119-cfa187b69dc4> in <module>()
37 writer.writerow(row)
38
---> 39 record("A/041/0.html")
40
41
<ipython-input-119-cfa187b69dc4> in record(part)
35 tds = tr.find_all('td')
36 row = [elem.text.encode('utf-8') for elem in tds[:4]]
---> 37 writer.writerow(row)
38
39 record("A/041/0.html")
ValueError: I/O operation on closed file
어떤 기능을해야 그냥 this 방향으로 테이블 스크랩
당신이 쓰기를 시도하고 파일이 열리지 않은하는ValueError: I/O operation on closed file
:
name은 만들고자하는 파일의 csv 이름입니다. – CreamStat