【问题标题】:Download HTML page and its contents下载 HTML 页面及其内容
【发布时间】:2010-12-21 23:29:02
【问题描述】:

Python 是否可以通过任何方式将整个 HTML 页面及其内容(images、css)下载到给定 url 的本地文件夹。并更新本地 html 文件以在本地选择内容。

【问题讨论】:

标签: python html


【解决方案1】:

您可以使用urllib 模块下载单个 URL,但这只会返回数据。它不会解析 HTML 并自动下载 CSS 文件和图像等内容。

如果您想下载“整个”页面,您需要解析 HTML 并找到您需要下载的其他内容。您可以使用 Beautiful Soup 之类的东西来解析您检索到的 HTML。

This question 有一些示例代码可以做到这一点。

【讨论】:

    【解决方案2】:

    您正在寻找的是镜像工具。如果你想要一个 Python,PyPI 列出了spider.py,但我没有这方面的经验。其他人可能会更好,但我不知道 - 我使用'wget',它支持getting the CSS 和图像。这可能是你想要的(引用the manual

    只检索一个 HTML 页面,但使 确保所需的所有元素 要显示的页面,例如 内嵌图像和外部样式 表,也下载了。也使 确保下载的页面引用 下载的链接。

    wget -p --convert-links http://www.server.com/dir/page.html
    

    【讨论】:

      【解决方案3】:

      你可以使用 urllib:

      import urllib.request
      
      opener = urllib.request.FancyURLopener({})
      url = "http://stackoverflow.com/"
      f = opener.open(url)
      content = f.read()
      

      【讨论】:

      • 这似乎只是下载一个考虑到 HTTP 响应代码的页面;除非我遗漏了什么,否则它实际上不会下载页面资源。
      • 不幸的是,现在已弃用:DeprecationWarning: FancyURLopener style of invoking requests is deprecated. Use newer urlopen functions/methods
      【解决方案4】:

      函数savePage 下面可以:

      • 在当前文件夹中保存.html
      • 基于标签scriptlinkimg下载javascriptscssimages
        • 保存在后缀为_files的文件夹中。
      • 任何异常都打印在sys.stderr
        • 返回一个BeautifulSoup 对象

      使用 Python 3+ RequestsBeautifulSoup 和其他标准库。

      函数savePage 接收urlfilename 保存它的位置。

      您可以扩展/调整它以满足您的需求

      import os, sys
      import requests
      from urllib.parse import urljoin
      from bs4 import BeautifulSoup
      import re
      
      def savePage(url, pagepath='page'):
          def soupfindnSave(pagefolder, tag2find='img', inner='src'):
              """saves on specified `pagefolder` all tag2find objects"""
              if not os.path.exists(pagefolder): # create only once
                  os.mkdir(pagefolder)
              for res in soup.findAll(tag2find):   # images, css, etc..
                  try:         
                      if not res.has_attr(inner): # check if inner tag (file object) exists
                          continue # may or may not exist
                      filename = re.sub('\W+', '', os.path.basename(res[inner])) # clean special chars
                      fileurl = urljoin(url, res.get(inner))
                      filepath = os.path.join(pagefolder, filename)
                      # rename html ref so can move html and folder of files anywhere
                      res[inner] = os.path.join(os.path.basename(pagefolder), filename)
                      if not os.path.isfile(filepath): # was not downloaded
                          with open(filepath, 'wb') as file:
                              filebin = session.get(fileurl)
                              file.write(filebin.content)
                  except Exception as exc:
                      print(exc, file=sys.stderr)
              return soup
          
          session = requests.Session()
          #... whatever other requests config you need here
          response = session.get(url)
          soup = BeautifulSoup(response.text, features="lxml")
          pagepath, _ = os.path.splitext(pagepath) # avoid duplicate .html
          pagefolder = pagepath+'_files' # page contents
          soup = soupfindnSave(pagefolder, 'img', 'src')
          soup = soupfindnSave(pagefolder, 'link', 'href')
          soup = soupfindnSave(pagefolder, 'script', 'src')
          with open(pagepath+'.html', 'wb') as file:
              file.write(soup.prettify('utf-8'))
          return soup
      

      示例google.com 保存为google.htmlgoogle_files 文件夹中的内容。 (当前文件夹

      soup = savePage('https://www.google.com', 'google')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-29
        • 2017-12-05
        • 1970-01-01
        • 2016-05-17
        • 1970-01-01
        • 2017-01-18
        相关资源
        最近更新 更多