无法使用python套接字编程下载文件

2024-10-01 07:32:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想用python套接字从这个url(http://justlearn.16mb.com/a.jpg)下载一个文件,我不知道怎么做,因为我是python的新手。你知道吗

实际上,我的主要目标是下载文件的一半使用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')     

Tags: 文件importcomhttpurlclosedatamb
2条回答

你可以试试这样的。由于代理的原因,我无法测试它,但是这个示例应该可以帮助您朝着正确的方向发展。直接使用套接字会使这变得不必要的困难。你知道吗

#! /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()

下面是另一个较短的示例,它使用urlopen包中的urllib.request函数。代码更简单,因为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()

文件有多大?我假设它大于1KB。写s.recv(1024)时,只接收1024字节。尝试使用更大的数字作为参数。你知道吗

它真的会更容易使用urllib.request请求,至少尝试一下,如果你不能“强制我的程序使用一个特定的网络适配器”,那么没关系。你知道吗

相关问题 更多 >