2011-12-18 5 views
4

Scrapy 스파이더를 사용하여 페이지를 긁어내어 해당 페이지를 읽을 수있는 형식의 .txt 파일로 저장하려고합니다. 내가이 일을 사용하고 코드는 다음과 같습니다 본문 내가 최종 제품 (주로 링크)에서 원하지 않는 HTML을 많이 포함하고 있기 때문에 내가 여기 BeautifulSoup로 결합했습니다Python에서 Scrapy로 텍스트 출력 서식 지정

def parse_item(self, response): 
     self.log('Hi, this is an item page! %s' % response.url) 

     hxs = HtmlXPathSelector(response) 

     title = hxs.select('/html/head/title/text()').extract() 
     content = hxs.select('//*[@id="content"]').extract() 

     texts = "%s\n\n%s" % (title, content) 

     soup = BeautifulSoup(''.join(texts)) 

     strip = ''.join(BeautifulSoup(pretty).findAll(text=True)) 

     filename = ("/Users/username/path/output/Hansard-" + '%s'".txt") % (title) 
     filly = open(filename, "w") 
     filly.write(strip) 

, 그래서 BS를 사용하여 HTML을 제거하고 관심있는 텍스트 만 남겨 두십시오.

나에게 내가 같이 출력이보고 싶어하지만

[u"School, Chandler's Ford (Hansard, 30 November 1961)"] 

[u' 

\n  \n 

    HC Deb 30 November 1961 vol 650 cc608-9 

\n 

    608 

\n 

    \n 


    \n 

    \n 

    \xa7 

    \n 

    28. 

    \n 


    Dr. King 


    \n 

    \n   asked the Minister of Education what is the price at which the Hampshire education authority is acquiring the site for the erection of Oakmount Secondary School, Chandler\'s Ford; and why he refused permission to acquire this site in 1954.\n 

    \n 

    \n 

\n  \n 

    \n 


    \n 

    \n 

    \xa7 

    \n 


    Sir D. Eccles 


    \n 

    \n   I understand that the authority has paid \xa375,000 for this site.\n   \n 

과 같은 출력을 제공합니다 : 나는 기본적으로 줄 바꿈 표시 \n를 제거하는 방법을 찾고 있어요 그래서

School, Chandler's Ford (Hansard, 30 November 1961) 

      HC Deb 30 November 1961 vol 650 cc608-9 

      608 

      28. 

Dr. King asked the Minister of Education what is the price at which the Hampshire education authority is acquiring the site for the erection of Oakmount Secondary School, Chandler's Ford; and why he refused permission to acquire this site in 1954. 

Sir D. Eccles I understand that the authority has paid £375,000 for this site. 

을 조 다 끝내고 특수 문자를 정상 형식으로 변환합니다. 코드에 대한 주석

답변

8

내 대답 : 귀하의 코멘트에 대한

import re 
import codecs 

#... 
#... 
#extract() returns list, so you need to take first element 
title = hxs.select('/html/head/title/text()').extract() [0] 
content = hxs.select('//*[@id="content"]') 
#instead of using BeautifulSoup for this task, you can use folowing 
content = content.select('string()').extract()[0] 

#simply delete duplicating spaces and newlines, maybe you need to adjust this expression 
cleaned_content = re.sub(ur'(\s)\s+', ur'\1', content, flags=re.MULTILINE + re.UNICODE) 

texts = "%s\n\n%s" % (title, cleaned_content) 

#look's like typo in filename creation 
#filename .... 

#and my preferable way to write file with encoding 
with codecs.open(filename, 'w', encoding='utf-8') as output: 
    output.write(texts) 
+0

감사합니다. 그러나 실행할 때마다 오류가 발생합니다 : \t'cleaned_content = re.sub (ur '(\ s) \ s +', ur '\ 1', 내용, flags = re.MULTILINE + re.UNICODE) \t exceptions.TypeError : sub()에 예기치 않은 키워드 인수 'flags'가 있습니다. 이견있는 사람? – user1074057

+0

@ user1074057 당신은 파이썬 <2.7 또는 <3.1을 사용하고 있습니다.이 경우 표현식을 컴파일해야합니다 :'strip_re = re.compile (ur '(\ s) \ s +', re.MULTILINE + re.UNICODE); cleaned_content = strip_re.sub (ur '\ 1', content)' – reclosedev

+0

완벽하게 작동합니다. 받아 들여지고 upvoted. 당신의 도움을 주셔서 감사합니다! – user1074057