因此,当我得到一些链接时,我想自动下载,假设链接是: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’在控制台?
谢谢
发布于 2018-04-30 08:20:47
下面是如何使用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请求库中开箱即用,因此user @CarsonLam提供了一个试图解决这个问题的答案这里。
库pypac提供了对此的支持,并且由于它继承自requests对象,因此它可以很好地处理现有代码。一些额外的pac示例可以找到这里。
有了一个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()https://stackoverflow.com/questions/50096286
复制相似问题