如何使用带有python脚本代码的pyQt 5 webengine下载文件?

时间:2018-04-30 07:59:53

标签: python pyqt5

所以当我得到一些链接时,我想自动下载, 让我们说链接是:http://test.com/somefile.avi

import os
import sys
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget, QWidgetAction
from PyQt5.QtCore import QUrl, QEventLoop
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEngineDownloadItem, QWebEnginePage


class WebPage(QWebEngineView):
    def __init__(self):
        QWebEngineView.__init__(self)
        self.load(QUrl("http://test.com"))
        self.loadFinished.connect(self._on_load_finished)
        self.n = 0

    def _on_load_finished(self):
        print("Finished Loading")
        self.page().toHtml(self.Callable)

    def Callable(self, html_str):
        self.html = html_str
        self.load(QUrl(userInput))

if __name__ == "__main__":
    userInput = input()
    app = QApplication(sys.argv)
    web = WebPage()

除了我只有'test.com'页面,但是我无法获得文件'somefile.avi',我可以在控制台中输入'http://test.com/somefile.avi'后自动下载吗?

由于

1 个答案:

答案 0 :(得分:0)

以下是如何使用requests

执行此操作的代码段

<强>声明

这个例子是用requests,python第三方库和用PyQt作为提问者最初的意图。

import requests
import shutil

def download(url):

    # gets the filename from the url, and
    # creates the download file absolute path
    filename = url.split("/")[-1]
    path = "downloads/" + filename

    # Defines relevant proxies, see `requests` docs
    proxies = {
      'http': 'http://10.10.1.10:3128',
      'https': 'http://10.10.1.10:1080',
    }

    # Add proxies, and leave `stream=True` for file downloads
    r = requests.get(url, stream=True, proxies=proxies)
    if r.status_code == 200:
        with open(path, 'wb') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)
    else:
        # Manually raise if status code is anything other than 200
        r.raise_for_status()


download('http://test.com/somefile.avi')

编辑:

pac文件不能与任何常见的python Web请求库一起使用,但是,SO用户@CarsonLam提供了一个试图解决此问题的答案here

pypac提供了对此的支持,并且由于它继承自requests个对象,因此它可以使用我们现有的代码。可以找到一些额外的pac示例here

使用pac代理文件,我猜这样的事情就是这样;

from pypac import PACSession, get_pac
import shutil

def download(url):

    # gets the filename from the url, and
    # creates the download file absolute path
    filename = url.split("/")[-1]
    path = "downloads/" + filename

    # looks for a pac file at the specified url, and creates a session
    # this session inherits from requests.Session
    pac = get_pac(url='http://foo.corp.local/proxy.pac')
    session = PACSession(pac)

    # Add proxies, and leave `stream=True` for file downloads
    session = requests.get(url, stream=True)
    if r.status_code == 200:
        with open(path, 'wb') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)
    else:
        # Manually raise if status code is anython other than 200
        r.raise_for_status()