是否有一种方法将这个shell代码移植到python?



我想从一个web服务器自动下载一个特定的文件,这个特定的web服务器不幸的是没有公共API,我可以使用,但他们发布了以下shell脚本下载文件。我的问题是我以前从未使用过shell脚本,所以我不知道如何移植shell代码,所以它在python中工作。我已经编写了一个与selenium一起工作的脚本来自动执行任务,但我不希望每次下载文件时都看到浏览器弹出。我已经知道如何使用请求来下载文件,但我不太理解"sed -n"。代码的一部分。我很感激任何帮助。Shell代码:

# Make sure the supplied URL looks valid
if [ "$(grep -Poc 'nopy.to/([a-zA-Z0-9]{8})/(.*?)$' <<< $1)" -lt 1 ]; then
echo -e " ! Error: Only nopy.to URLs are supportedn"
exit 1
fi
# Parse the code and file from URL
code=`echo $1 | sed -n 's/.*nopy.to/([a-zA-Z0-9]{8})/.*/1/p'`
file=`echo $1 | sed -n 's/.*nopy.to/[a-zA-Z0-9]{8}/(.*)/?/1/p'`
# Fetch the session
echo -e " Fetching session ...n"
sessionreq=`curl -s --data-urlencode "code=$code" --data-urlencode "file=$file" -X POST https://data.nopy.to/file`
if [ "$(echo $sessionreq | jq -r '.status')" != "ok" ]; then
echo -e " ! Error: Session request failedn"
exit 1
fi
if [ "$(echo $sessionreq | jq -r '.msg.error_fatal')" != "false" ]; then
echo -e " ! Error: Nopy is having technical issuesn"
exit 1
fi
if [ -f "$(echo $sessionreq | jq -r '.msg.filename')" ]; then
echo -e " ! Error: File "$(echo $sessionreq | jq -r '.msg.filename')" already existsn"
exit 1
fi
# Fetch the download URL
echo -e " Requesting download ticket ...n"
downloadreq=`curl -s --data-urlencode "code=$code" --data-urlencode "fid=$(echo $sessionreq | jq -r '.msg.fid')" --data-urlencode "request=$(echo $sessionreq | jq -r '.msg.request')" --data-urlencode "session=$(echo $sessionreq | jq -r '.msg.session')" -X POST https://data.nopy.to/download`

你可以使用requests模块来完成这个任务。

我也做了一个类似的脚本。它可能对你有帮助:-

from __future__ import division
from tqdm import tqdm # for progress bar
import requests # for downloading
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
url = input('Enter URL : ')

buffer = 8000
# download the body of response by chunk, not immediately
response = requests.get(url,stream = True,verify = False)
# get the total file size
cl = response.headers.get("Content-Length")
if cl == None :
file_size = None
else :
file_size = int(cl)
# get the file name
name = input("Enter File Name :")
if name :
filename = name
else :
filename = url.split("/")[-1].split("?")[0]

def dl() :
print("Download Size :",round(file_size/1048576,1),"MB")
print()
progress = tqdm(response.iter_content(buffer), f"Downloading {filename}", total=file_size, unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "wb") as file:
for data in progress:
file.write(data)
progress.update(len(data))
def fdl() :
print("Download Size : Unknown (∞)")
# Someone edit the answer and complete this function. My one didn't work.
if file_size == None :
fdl() # when Download size is unknown from header
else :
dl() # when Download size is known from header
print("Downloading Finished !n")

相关内容

  • 没有找到相关文章

最新更新