如何使用urllib下载整个网站?

时间:2013-10-16 08:46:50

标签: python

我需要使用python urlib下载整个网站 喜欢

import urllib

site = urllib.urlopen('http://www.mathrubumi.com/index.php')
site_data = site.read()

仅下载第一页。那是index.php。如何使代码下载整个网站。 通过循环? 或者还有其他方法吗? 例如,在wget代码中不需要循环

wget \ --recursive \--no-clobber \ --page-requisites \ --html-extension \  --convert-links \
     --restrict-file-names=windows \ --domains website.org \    --no-parent \    www.website.org/tutorials/html/

3 个答案:

答案 0 :(得分:5)

如果您想下载一个包含urllib的完整网站,您将需要解析每个页面,找到所有链接并下载它们。这是可行的,但要做到正确可能会很棘手。

如果你想要一个纯python解决方案,或者只是从你的脚本中调用wget,我建议你查看scrapy

答案 1 :(得分:1)

由于用户(在另一个问题中,但由于..原因而被删除..)指出了使用BeautifulSoup作为替代方案的引用,这里有一个工作示例来检索所有<a href="something.html">something</a>链接并将其保存在本地:

import urllib2
from BeautifulSoup import BeautifulSoup, SoupStrainer
from os.path import basename

def store_links(page):
    with open(basename(page), 'wb') as fh:
        site = urllib.urlopen(page)
        site_data = site.read()

        fh.write(site_data)

        for link in BeautifulSoup(site_data, parseOnlyThese=SoupStrainer('a')):
            if link.has_attr('href'):
                store_links(link['href'])

store_links('http://www.nytimes.com')

注意:已经过测试,目前处于锁定的机器上,因此可能会出现语法错误,但想法是一样的:

  1. 创建一个递归函数,只要找到链接就会自动调用
  2. 给那个递归函数一个起点,让它坚持下去

答案 2 :(得分:0)

  1. 如果您没有使用urlencode方法,那么您可以使用urllib2,它允许您设置标题和UA。或者您可以使用支持更多API的请求。 See documentation here
  2. 要使用urllib下载整个网站,网站必须启用目录列表,大多数网站所有者都不会通过设置.htaccess来允许。