2

您好,我只是想知道我正在尝试创建一个从 Internet 下载文件的 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-

4

1 回答 1

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)

剩下的就看你了。download_game()根据游戏的 URL 下载游戏,因此您必须找出<object>标签在 DOM 中的位置。

于 2012-12-09T09:39:59.710 回答