2016-09-08 3 views
1

파이썬 소켓만을 사용하여이 URL (http://justlearn.16mb.com/a.jpg)에서 파일을 다운로드하고 파이썬에서 초보자로서 사용하는 방법을 모릅니다.파이썬 소켓 프로그래밍을 사용하여 파일을 다운로드 할 수 없습니다.

실제로 내 주요 목표는 이더넷 연결을 사용하여 wifi 연결과 다른 절반 부분을 사용하여 파일을 절반으로 다운로드하는 것입니다.

도움을 주셔서 감사합니다.

import os 
import socket 

tcpd = 'http://justlearn.16mb.com/a.jpg' 
portd = 80 
ipd = socket.gethostbyname('http://justlearn.16mb.com/a.jpg') 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((tcpd,portd)) 



BUFFER_SIZE = 1024 

with open('a.jpg', 'wb') as f: 
    print ('file opened') 
    while True: 
     #print('receiving data...') 
     data = s.recv(1024) 
     #print('data=%s', (data)) 
     if not data: 
      f.close() 
      break 
     # write data to a file 
     f.write(data) 

print('Successfully get the file') 
s.close() 
print('connection closed')  

답변

0

다음과 같이 시도해보십시오. 프록시 때문에 테스트 할 수 없지만 예제가 올바른 방향으로 도움이 될 것입니다. 소켓을 직접 사용하면 불필요하게 어렵게됩니다. 여기

#! /usr/bin/env python3 
import http.client 


def main(): 
    connection = http.client.HTTPConnection('justlearn.16mb.com') 
    connection.request('GET', '/a.jpg') 
    response = connection.getresponse() 
    if response.status != 200: 
     raise RuntimeError(response.reason) 
    with open('a.jpg', 'wb') as file: 
     while not response.closed: 
      buffer = response.read(1 << 12) 
      if not buffer: 
       break 
      file.write(buffer) 
    connection.close() 


if __name__ == '__main__': 
    main() 

은 짧은 대신 urllib.request 패키지에서 urlopen 함수를 사용하는 또 다른 예이다. 코드는 백그라운드에서 HTTP 코드가 처리되므로 더 간단합니다.

#! /usr/bin/env python3 
from urllib.request import urlopen 


def main(): 
    with urlopen('http://justlearn.16mb.com/a.jpg') as source, \ 
      open('a.jpg', 'wb') as destination: 
     while True: 
      buffer = source.read(1 << 12) 
      if not buffer: 
       break 
      destination.write(buffer) 


if __name__ == '__main__': 
    main() 
+0

감사합니다,하지만 다음이 URLLIB 또는 http.client lib 디렉토리를 사용하여, 난 내가이 인터넷에 연결 한 무선 랜과 이더넷을 가지고있는 것처럼 특정 네트워크 어댑터를 사용하여 내 프로그램을 강제 할 수 없습니다 생각합니다. 내가 wifi를 사용하여 브라우저에서 서핑을하고 싶을 때 이더넷을 사용하여 다운로드 할 수 있습니다. –

+0

@SAGARAGRAWAL 어떻게 특정 네트워크 어댑터를 코드에서 사용하도록 강요합니까? –

+0

특정 네트워크 인터페이스 또는이 s.bind (('192.168.0.1', 0))에서 특정 대상 IP에 특정 경로를 추가하기 위해 Windows 기본 netsh 명령을 사용하려고 생각합니다. s.connect (('...')) –