我只想用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')
你可以试试这样的。由于代理的原因,我无法测试它,但是这个示例应该可以帮助您朝着正确的方向发展。直接使用套接字会使这变得不必要的困难。你知道吗
下面是另一个较短的示例,它使用
urlopen
包中的urllib.request
函数。代码更简单,因为HTTP代码是在后台处理的。你知道吗文件有多大?我假设它大于1KB。写
s.recv(1024)
时,只接收1024字节。尝试使用更大的数字作为参数。你知道吗它真的会更容易使用urllib.request请求,至少尝试一下,如果你不能“强制我的程序使用一个特定的网络适配器”,那么没关系。你知道吗
相关问题 更多 >
编程相关推荐