【问题标题】:cannot downloads file using python socket programming无法使用python套接字编程下载文件
【发布时间】:2017-01-16 19:06:26
【问题描述】:

我想只使用 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')     

【问题讨论】:

    标签: python sockets wifi ethernet download-manager


    【解决方案1】:

    您可能想尝试类似的方法。由于代理,我无法对其进行测试,但是该示例应该可以帮助您朝着正确的方向发展。直接使用套接字会使这变得不必要地困难。

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

    【讨论】:

    • 谢谢,但是通过使用这个 urllib 或 http.client lib,我想我将无法强制我的程序使用特定的网络适配器,就像我有两个互联网连接一个 wifi 和以太网.我希望能够使用以太网下载,而我想使用 wifi 在浏览器中冲浪
    • @SAGARAGRAWAL 您如何强制在代码中使用特定的网络适配器?
    • 我正在考虑使用 Windows 本机 netsh 命令从特定网络接口或此 s.bind(('192.168.0.1', 0)) s.connect(( '...'))
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-08-10
      • 1970-01-01
      • 2011-02-09
      • 2020-03-18
      • 1970-01-01
      • 2020-02-28
      • 2022-01-18
      • 2016-02-20
      • 1970-01-01
      相关资源
      最近更新 更多