【发布时间】:2021-01-27 02:36:58
【问题描述】:
我想自动从网络服务器下载特定文件,不幸的是,这个特定的网络服务器没有我可以使用的公共 API,但他们发布了以下 shell 脚本来下载文件。我的问题是我以前从未使用过 shell 脚本,所以我不知道如何移植 shell 代码以便它在 python 中工作。我编写了一个与 selenium 一起使用的脚本来自动执行任务,但我不希望每次下载文件时都弹出浏览器。我已经知道如何使用请求来下载文件,但我并不真正理解代码的“sed -n”部分。我感谢任何形式的帮助。 外壳代码:
# 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 supported\n"
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 failed\n"
exit 1
fi
if [ "$(echo $sessionreq | jq -r '.msg.error_fatal')" != "false" ]; then
echo -e " ! Error: Nopy is having technical issues\n"
exit 1
fi
if [ -f "$(echo $sessionreq | jq -r '.msg.filename')" ]; then
echo -e " ! Error: File \"$(echo $sessionreq | jq -r '.msg.filename')\" already exists\n"
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`
【问题讨论】:
-
是的,它可以使用“请求”模块来完成。如果你愿意,我可以私下分享我的项目代码。我使用请求做了类似的事情。
-
@TanishqBanyal 当然,如果可以提供帮助,我愿意接受任何事情。感谢您提供这个。您将如何“私下”与我分享?
-
我将在下面创建一个答案。
标签: python python-3.x shell