2016-10-01 2 views
0

OED.com 웹 사이트 단어의 제목과 날짜를 긁어서 목록으로 인쇄하는 아래 코드를 작성했습니다.스크랩 한 목록을 CSV 파일에 저장하는 방법은 무엇입니까?

import requests 
import re 
import urllib2 
import os 
import csv 

year_search = 1550 
subject_search = ['Law'] 

path = '/Applications/Python 3.5/Economic' 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) 
urllib2.install_opener(opener) 

user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' 
header = {'User-Agent':user_agent} 
request = urllib2.Request('http://www.oed.com/', None, header) 
f = opener.open(request) 
data = f.read() 
f.close() 
print 'database first access was successful' 

resultPath = os.path.join(path, 'OED_table.csv') 
htmlPath = os.path.join(path, 'OED.html') 
outputw = open(resultPath, 'w') 
outputh = open(htmlPath, 'w') 
request = urllib2.Request(
    'http://www.oed.com/search?browseType=sortAlpha&case-insensitive=true' 
    '&dateFilter='+str(year_search)+'&nearDistance=1&ordered=false&page=1' 
    '&pageSize=100&scope=ENTRY&sort=entry&subjectClass=' 
    + str(subject_search) + '&type=dictionarysearch', None, header) 
page = opener.open(request) 
urlpage = page.read() 
outputh.write(urlpage) 
new_word = re.findall(
    r'<span class=\"hwSect\"><span class=\"hw\">(.*?)</span>', urlpage) 
print str(new_word) 
outputw.write(str(new_word)) 
page.close() 
outputw.close() 

는 지금은 매년 I 입력이 행으로 배치됩니다 같은 방법으로 CSV 파일로하지만 그들을 인쇄 할, 그리고 낱말 행의 라인에있는 모든 가을 것. 등을

정렬 :

1550| word1| word2| etc.| 
1551| word1| word2| etc.| 

사람이 어떤 아이디어가 있습니까?

+0

나는 (코드 1550에서) 1 년, 그리고 (코드'new_word'에서) 단어 목록을 가졌음을 이해했다. 그러나 나는 당신이 1 년 이상 단어의 그룹을 어디에 저장하고 있는지 보지 못합니다. 1 년 중 해당하는 행을 표시하는 것으로 충분합니까? –

+0

스크랩이 작동하지 않는 것 같습니다. 나는 여러 가지 'year_search'값을 시도해 보았고, 모두 똑같은 것을 반환했다. 그냥 [[nicker ']'로 구성된 목록이다. 질문을 편집하고 둘 이상의 값을 반환하는 것으로 변경하십시오. – martineau

답변

1

csv.writer 방법을 사용하는 것이 좋습니다. 다음 샘플 코드는 다음과 같습니다

`

with open('/Applications/Python 3.5/Economic/OED_table.csv', 'w') as csv_file: 
    csv_writer = csv.writer(csv_file) 
    year = ["1550"] 
    new_word = ["apple", "banana"] 
    complete_row = year + new_word 
    csv_writer.writerow(complete_row) 
    # writes 1550, apple, banana to OED_table.csv 

`

여러 행을 삽입하는 for 루프로 수정할 수 있습니다

. 당신이 new_word하면 다음과 같은 작업을 수행 할 수 정의 선 후

+0

이것은 완벽합니다. 고맙습니다. – Kainesplain

0

: 등 | | 단어 1 | word2

year_info = [str(year_search)] + new_word 
print '|'.join(year_info) 

이 출력됩니다 정확히

1550 |

관련 문제