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

2024-09-30 20:19:37 发布

您现在位置: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/

Tags: no代码orgimportindex网站htmlwww
3条回答
  1. 如果不使用urlencode方法,那么可以使用urllib2,它允许您设置头和UA。或者可以使用支持更多API的请求。See documentation here
  2. 若要使用urllib下载整个网站,网站必须启用目录列表,而大多数网站所有者都不允许通过在.htaccess中设置目录列表。

自从用户(在另一个问题中被问到但被删除是因为。。原因..)指出了使用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. 给递归函数一个起点,让它发疯

如果你想下载一个完整的带有urllib的网站,你必须解析每个页面,找到所有链接并下载它们。这是可行的,但要做到正确却很难。

如果您想要纯python解决方案,我建议您查看scrapy,或者从脚本中调用wget

相关问题 更多 >