Python -> 从网络文件夹中获取所有有效的媒体下载网址



我这里有一个网站,它的链接结构是这样的

https://example.com/assets/contents/1627347928.mp4
https://example.com/assets/contents/1627342345.mp4
https://example.com/assets/contents/1627215324.mp4

我想使用python来获取所有链接下载,当我访问文件夹/assets/contents/时,我得到一个404错误,所以我无法看到从这个web文件夹下载的所有媒体,但我知道所有的MP4文件都有10个字符,并且都以"1627******.mp4"我可以做一个循环检查从该网站的所有链接,并得到所有有效的链接?谢谢 !!!!!!!!!!!!我现在是python的新手!

我可以检查是否有媒体mp4/媒体与代码,我可以看到一个文件的头,但如何使循环检查所有的链接和自动下载?还是只显示有效的链接?谢谢! !

import requests
link = 'https://example.com/assets/contents/1627347923.mp4'
r = requests.get(link, stream=True)
print(r.headers)

打印文件是否存在

import requests
names = [ 1627347923, 1627347924, 1627347925]
base = 'https://example.com/assets/contents/{}.mp4'
for item in names:
link = base.format(item)
print(link)
r = requests.head(link, allow_redirects=True)
if r.status_code == 200:
print("found {}.mp4".format(item))
#open('{}.mp4'.format(item), 'wb').write(r.content)
else:
print("File no found or error getting headers")

或者尝试下载

import requests
names = [ 1627347923, 1627347924, 1627347925]
base = 'https://example.com/assets/contents/{}.mp4'
for item in names:
link = base.format(item)
print(link)
# uncomment below to download
#r = requests.get(link, allow_redirects=True)
#open('{}.mp4'.format(item), 'wb').write(r.content)

是的,你可以运行一个循环,检查状态码,或者如果request .get()抛出一个错误,你会得到返回的所有文件,但是有一些问题可能会阻止你选择

  1. 您的文件格式为"1627******.mp4",这意味着for循环将检查10^6个条目,如果所有*都是数字,这是不高效的。如果您计划包含字符和特殊字符,那么效率将非常低。

  2. 如果将来你有超过10^6个文件怎么办?你的格式必须改变,所以你的代码也必须改变。

一个更简单,直接和有效的解决方案是有一个地方来存储你的数据,一个文件或更好的数据库,在那里你可以查询和获得你所有的文件。您可以直接运行查询以获取必要的详细信息。

同样,404错误意味着你试图到达的页面没有找到,在你的情况下,它本质上意味着它不存在。

一个示例代码A/c检查链接是否存在

files = []
links = ["https://www.youtube.com/","https://docs.python.org","https://qewrt.org"]
for i in links:
try:
requests.get(i) // If link doesnt exists, it throws an error, else the link is appended to the files list
files.append(i)
except:
print(i+" doesnt exist")
print(files)

在此基础上,根据您的条件,检查所有文件是否以给定格式存在:

import requests
file_prefix = 'https://example.com/assets/contents/1627'
file_lists = []
for i in range(10**6):
suffix = (6-len(str(i)))*"0"+str(i)+".mp4"
file_name = file_prefix+suffix
try:
requests.get(file_name)
file_lists.append(file_name)
except:
continue
for i in file_lists:
print(i)

基于您的所有代码和LMC代码,我做了一件事,谁测试了所有的MP4文件,并向我展示了"头文件",我如何只能选择具有MP4有效文件的链接,如链接

import requests
file_prefix = 'https://example.com/assets/contents/1627'
file_lists = []
for i in range(10**6):
suffix = (6-len(str(i)))*"0"+str(i)+".mp4"
file_name = file_prefix+suffix
try:
requests.get(file_name)
file_lists.append(file_name)
r = requests.get(file_name, stream=True)
print(file_name)        
print(r.headers)
except:
continue
for i in file_lists:
print(i)

最新更新