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

Ter*_*rii 1 python download urllib2

你好我只是想知道我正在尝试创建一个从互联网上下载文件的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()
Run Code Online (Sandbox Code Playgroud)

那么它是从这个网站下载taxi.swf但是我想要它的目的是从目录"/"下载所有.swf到计算机?

有可能并且非常感谢你的进步.-Terrii-

Ble*_*der 6

由于您尝试一次下载大量内容,首先要查找网站索引或网页,其中列出了您要下载的所有内容.该网站的移动版本通常比桌面更轻,更容易刮.

这个网站正是您正在寻找的:所有游戏.

现在,它真的很简单.只是,提取所有游戏页面链接.我使用BeautifulSoup请求执行此操作:

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)
Run Code Online (Sandbox Code Playgroud)

剩下的由你决定.download_game()在给定游戏URL的情况下下载游戏,因此您必须<object>在DOM中找出标记的位置.