gpt4 book ai didi

python - 使用 Python 列出在线目录中的所有文件?

转载 作者:太空宇宙 更新时间:2023-11-04 08:16:19 27 4
gpt4 key购买 nike

你好,我只是想知道我正在尝试创建一个从互联网下载文件的 python 应用程序,但目前它只下载一个我知道名称的文件...有什么办法可以得到一个列表在线目录中的文件并下载它们?我会向您展示我一次下载一个文件的代码,只是让您知道我不想做什么。

import urllib2

url = "http://cdn.primarygames.com/taxi.swf"

file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)

file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break

file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,

f.close()

那么它从该网站下载 taxi.swf 是做什么的,但我想要它做的是从该目录“/”下载所有 .swf 到计算机?

有可能吗,非常感谢你。 -Terrii-

最佳答案

由于您正尝试一次下载大量内容,因此请先寻找一个站点索引或一个整齐地列出您要下载的所有内容的网页。网站的移动版本通常比桌面版本更轻,更容易抓取。

这个网站正是您要找的东西:All Games .

现在,这真的很简单。只是,提取所有游戏页面链接。我用 BeautifulSouprequests这样做:

import requests
from bs4 import BeautifulSoup

games_url = 'http://www.primarygames.com/mobile/category/all/'

def get_all_games():
soup = BeautifulSoup(requests.get(games_url).text)

for a in soup.find('div', {'class': 'catlist'}).find_all('a'):
yield 'http://www.primarygames.com' + a['href']

def download_game(url):
# You have to do this stuff. I'm lazy and won't do it.

if __name__ == '__main__':
for game in get_all_games():
download_game(url)

剩下的就看你了。 download_game()根据游戏的 URL 下载游戏,所以你必须找出 <object> 的位置DOM 中的标记。

关于python - 使用 Python 列出在线目录中的所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13786210/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com