2016-06-19 1 views
0
def crawl(url): 
    html = getHTML(url) # getHTML() retruns HTTPResponse 
    print(html.read()) # PRINT STATMENT 1 
    if (html == None): 
     print("Error getting HTML") 
    else: 
     # parse html 
     bsObj = BeautifulSoup(html, "lxml") 
     # print data 
     try: 
      print(bsObj.h1.get_text()) 
     except AttributeError as e: 
      print(e) 

     print(html.read()) # PRINT STAETMENT 2 

내가 이해하지 못하는 것은입니다 ..인쇄 같은 HttpResponse에 개체는 서로 다른 출력을 반환 - 파이썬

PRINT 문 1 인쇄 전체 HTML 반면 PRINT 문이 만 인쇄 b''

여기서 무슨 일이 일어나고있는거야? .. 나는 Python을 처음 접했습니다.

+0

'html == None'을 제외하면됩니다. http://stackoverflow.com/questions/14247373/python-none-comparison-should-i-use-is-or를 참조하십시오. – edwinksl

+0

@edwinksl ty .. 도움이됩니다. – reversiblean

답변

1

html은 HTTPResponse 개체입니다. HTTPResponse는 read()과 같은 파일과 같은 작업을 지원합니다.

파일을 읽을 때와 마찬가지로 read()은 사용 가능한 데이터를 사용하고 파일 포인터를 파일/data의 으로 이동합니다. 후속 read()은 반환 할 것이 없습니다.

print(html.read()) 
html.seek(0) # moves the file pointer to byte 0 relative to the start of the file/data 
  • 저장하는 대신 결과 :

    html_body = html.read() 
    print(html_body) 
    
  • seek() 방법을 사용하여 읽은 후

    1. 가 처음으로 파일 포인터를 재설정

      당신은 두 가지 옵션이 있습니다

      일반적으로 재사용하기 쉽기 때문에 두 번째 옵션을 사용합니다. html_body