2014-05-21 6 views
1

나는 파이썬 3을 사용하여 웹에서 읽으려고 시도하고 모든 라인을 하나씩 인쇄하려고한다.파이썬 3 웹 페이지를 라인

내가 지금까지 본 가장 좋은 방법은 이런 식으로 뭔가를해야만 urllib.request 사용 할 수있다 :

import urllib.request 
url_target = urllib.request.urlopen("http://stackoverflow.com") 
tmp_copy_string = url_target.read().decode("utf8") 
file = "file" 
for word in tmp_copy_string: 
     print(word) 

내가 말씀으로이 코드를 인쇄 단어를 생각 - 그것은 dosnt ....

문제 단어 단위로 단어를 인쇄하는 것이 아니라 문자로 문자를 인쇄하는 것입니다 ...

줄 단위로 인쇄하는 좋은 방법이 있습니까?

추가 라이브러리를 사용하지 않아도됩니다.

+0

내 2 센트 => urllib를 통한 httplib2 사용을 제안합니다. 나중에 코드 리팩토링을 피할 수있는 포괄적 인 것으로 나타납니다. @ https://github.com/jcgregorio/httplib2를 확인하십시오. –

답변

2

당신은 \n하여 분할 할 수 있습니다 :

import urllib.request 

url_target = urllib.request.urlopen("http://stackoverflow.com") 
tmp_copy_string = url_target.read().decode("utf8").split('\n') #split string on newline 

for line in tmp_copy_string: 
     print(line) 

이 줄

0

내가 URL에 대한 요청을하려고 할 때 requests 라이브러리를 사용하여 제안하여 코드 라인을 인쇄합니다. 사용하기 쉽고 문서화가 잘되어 있습니다. pip install requests을 통해 설치할 수 있습니다.

이제 텍스트를 줄 바꿈으로 나누려면 .split('\n')을 사용할 수 있지만이 상황은 너무 일반적이어서 .splitlines()의 또 다른 기능이 있습니다. 여기에 텍스트를 디코딩하지 않고 세션이, 그래서 텍스트가 유니 코드에 있습니다

당신은 iter를 사용할 필요가 없습니다
>>> import requests 
>>> var = requests.get("http://stackoverflow.com") 
>>> lines = var.text.splitlines() 
>>> lines_iter = iter(lines) 
>>> next(lines_iter) 
u'<!DOCTYPE html>' 
>>> next(lines_iter) 
u'<html>' 
>>> next(lines_iter) 
u'<head>' 
>>> next(lines_iter) 
u' ' 
>>> next(lines_iter) 
u' <title>Stack Overflow</title>' 
>>> next(lines_iter) 
u' <link rel="shortcut icon" href="//cdn.sstatic.net/stackoverflow/img/favicon.ico?v=038622610830">' 
>>> next(lines_iter) 
u' <link rel="apple-touch-icon image_src" href="//cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png?v=fd7230a85918">' 
>>> next(lines_iter) 
u' <link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="/opensearch 

splitlines 목록을 반환, 당신은 반복 할 수있는 for 루프를 사용. 하지만 여기에 iter을 사용했습니다.