2012-12-18 4 views
1

웹 사이트의 내용을 파이썬으로 긁어 내고 싶습니다. 다만이 같은 :파이썬으로 데이터 스크래핑을 인코딩하기

Apple’s stock continued to dominate the news over the weekend, with Barron’s placing it on the top of its favorite 2013 stock list. 

그러나 오류 결과로 인쇄 :

Apple âs stock continued to dominate the news over the weekend, with Barronâs placing it on the top of its favorite 2013 stock list. 

기호 " '"표시 할 수 없습니다가 여기 내 코드입니다 : 그러나

#-*- coding: utf-8 -*- 

    import sys 
    reload(sys) 
    sys.setdefaultencoding('utf-8') 
    import urllib 
    from lxml import * 
    import urllib 
    import lxml.html as HTML 

    url = "http://www.forbes.com/sites/panosmourdoukoutas/2012/12/09/apple-tops-barrons- 10-favorite-stocks-for-2013/?partner=yahootix" 
    sock = urllib.urlopen(url) 
    htmlSource = sock.read() 
    sock.close() 

    root = HTML.document_fromstring(htmlSource) 
    contents = ' '.join([x.strip() for x in root.xpath("//div[@class='body']/descendant::text()")]) 

    print contents 

    f = open('C:/Users/yinyao/Desktop/Python Code/data.txt','w') 
    f.write(contents) 
    f.close() 

, 설정 후 printf의 기능은 유용하지 않습니다. 왜? 그리고 어떻게해야합니까? 저는 Windows를 사용하고 있으며 기본 인코딩 방식은 gbk입니다.

+0

당신이 스크래핑을하고 코드를 게시 할 수 사용할 수 있습니까? –

+0

명세서를 어떻게 인쇄하고 있습니까? 명령문을 인쇄하기 위해 실행 한 정확한 명령을 게시하십시오. 파이썬에는 printf 함수가 없습니다. – stackoverflowery

+1

[Beautiful Soup] 시도 (http://www.crummy.com/software/BeautifulSoup/) –

답변

1

첫째, 당신은 The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

둘째, 내부 항상 사용 유니 코드를 알고 있는지 확인합니다. 일찍 해독하고 늦게 인코딩하십시오. 웹 사이트를 스크랩하고 유니 코드로 디코딩 한 다음 스크립트에서 내부적으로 유니 코드로 처리하십시오. 그렇지 않으면 임의의 지점에서 코드가 충돌합니다. 예를 들어 중국어의 일부 웹 페이지에서 주석에 예기치 않은 문자가 발생했기 때문입니다. 당신은 (일부 쓰기 스트림에, 예를 들어,) 나중에 곳을 통과 할 때 단지 당신이 그것을 인코딩해야합니다 ("UTF-8"바람직)

셋째, BeautifulSoup 4

+0

감사합니다! 그러나 유니 코드로 웹 사이트 데이터를 디코딩 할시기와 방법을 모르겠습니다. 내 질문을 다시 작성하고 코드를 표시했습니다. 코드에 대한 제안을 더 줄 수 있습니까? – yinyao

+0

먼저 질문을 * 올바르게 형식화하십시오. http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks. 코드를 읽을 수 있습니다. 둘째, BautifulSoup가 유니 코드를 처리합니다. –

+0

감사합니다! BeautifulSoup는 유용하지만 htmlSource를 유니 코드로 디코딩하여 해결했습니다. – yinyao

관련 문제