首页 > 解决方案 > Scrapy:保存网站

问题描述

我正在尝试在他们在月底取消 wikispace 之前保存pyparsing项目的副本。wikispaces.com

看起来很奇怪(也许我的谷歌版本坏了^_^)但我找不到任何复制/复制网站的例子。也就是说,正如人们在浏览器上查看的那样。SO 在主题上有这个这个,但他们只是为网站保存文本,严格来说是 HTML/DOM 结构。除非我弄错了,否则这些 asnwers 似乎不会保存呈现页面所需的图像/标题链接文件/javascript 和相关信息。我看到的更多示例更关注提取页面的某些部分,而不是按原样复制它。

我想知道是否有人对这类事情有任何经验,或者可以将我指向某个有用的博客/文档。我过去曾使用WinHTTrack过,但robots.txtpyparsing.wikispaces.com/auth/路线阻止它正常运行,我想我会获得一些scrapy经验。

对于那些有兴趣看看我迄今为止尝试过的人。这是我的爬虫实现,它承认robots.txt文件

import scrapy
from scrapy.spiders import SitemapSpider
from urllib.parse import urlparse
from pathlib import Path
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class PyparsingSpider(CrawlSpider):
 name = 'pyparsing'
 allowed_domains = ['pyparsing.wikispaces.com']
 start_urls = ['http://pyparsing.wikispaces.com/']

 rules = (
     Rule(LinkExtractor(), callback='parse_item', follow=True),
 )

 def parse_item(self, response):
#   i = {}
#   #i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()
#   #i['name'] = response.xpath('//div[@id="name"]').extract()
#   #i['description'] = response.xpath('//div[@id="description"]').extract()
#   return i
  page = urlparse(response.url)
  path = Path(page.netloc)/Path("" if page.path == "/" else page.path[1:])
  if path.parent : path.parent.mkdir(parents = True, exist_ok=True) # Creates the folder
  path = path.with_suffix(".html")
  with open(path, 'wb') as file:
   file.write(response.body)

用站点地图蜘蛛尝试同样的事情是相似的。第一个SO链接提供了一个带有普通蜘蛛的实现。

import scrapy
from scrapy.spiders import SitemapSpider
from urllib.parse import urlparse
from pathlib import Path

class PyParsingSiteMap(SitemapSpider) :

 name = "pyparsing"
 sitemap_urls = [ 
                  'http://pyparsing.wikispaces.com/sitemap.xml', 
#                   'http://pyparsing.wikispaces.com/robots.txt', 
                ]
 allowed_domains = ['pyparsing.wikispaces.com']
 start_urls = ['http://pyparsing.wikispaces.com'] # "/home"
 custom_settings = {
  "ROBOTSTXT_OBEY" : False
 }

 def parse(self, response) :
  page = urlparse(response.url)
  path = Path(page.netloc)/Path("" if page.path == "/" else page.path[1:])
  if path.parent : path.parent.mkdir(parents = True, exist_ok=True) # Creates the folder
  path = path.with_suffix(".html")
  with open(path, 'wb') as file:
   file.write(response.body) 

这些蜘蛛都没有收集比 HTML 结构更多的东西

我还发现<a href="...">...</a>保存的链接似乎没有指向正确的相对路径。至少,当打开保存的文件时,链接指向相对于硬盘驱动器的路径,而不是相对于文件的路径。虽然通过链接打开页面http.server指向死区,但.html扩展可能是这里的麻烦。可能需要重新映射/替换存储结构中的链接。

标签: scrapyscrapy-spiderarchiving

解决方案


推荐阅读