使用保存在本地系统中的html来抓取文件

Shi*_*dla 21 python scrapy

例如,我有一个网站"www.example.com" 其实我想通过保存到本地系统刮掉这个网站的HTML.所以为了测试我在桌面上保存了那个页面example.html

现在我已经为此编写了蜘蛛代码,如下所示

class ExampleSpider(BaseSpider):
   name = "example"
   start_urls = ["example.html"]

   def parse(self, response):
       print response
       hxs = HtmlXPathSelector(response)
Run Code Online (Sandbox Code Playgroud)

但是当我运行上面的代码时,我收到如下错误

ValueError: Missing scheme in request url: example.html
Run Code Online (Sandbox Code Playgroud)

最后我的意思是刮掉example.htmlwww.example.com本地系统中保存的html代码组成的文件

任何人都可以建议我如何在start_urls中分配该example.html文件

提前致谢

iod*_*dbh 24

您可以使用以下格式的网址抓取本地文件:

 file:///path/to/file.html
Run Code Online (Sandbox Code Playgroud)

它不需要在您的计算机上安装http服务器.

  • 它不起作用,但文件:///path/to/file.html - 确实如此 (6认同)

Sja*_*aak 9

您可以使用HTTPCacheMiddleware,它将使您能够从缓存运行蜘蛛.HTTPCacheMiddleware设置的文档位于此处.

基本上,将以下设置添加到settings.py将使其工作:

HTTPCACHE_ENABLED = True
HTTPCACHE_EXPIRATION_SECS = 0 # Set to 0 to never expire
Run Code Online (Sandbox Code Playgroud)

但是,这需要从Web执行初始蜘蛛运行以填充缓存.


Gau*_*mar 5

在scrapy中,您可以使用以下方法抓取本地文件:

class ExampleSpider(BaseSpider):
   name = "example"
   start_urls = ["file:///path_of_directory/example.html"]

   def parse(self, response):
       print response
       hxs = HtmlXPathSelector(response)
Run Code Online (Sandbox Code Playgroud)

我建议你使用scrapy shell 'file:///path_of_directory/example.html' 检查它


Den*_*nis -6

如果您查看 scrapy Request 的源代码,例如github。您可以了解 scrapy 向 http 服务器发送请求并从服务器响应中获取所需的页面。您的文件系统不是 http 服务器。为了使用 scrapy 进行测试,您必须设置 http 服务器。然后你可以将url分配给scrapy,例如

http://127.0.0.1/example.html
Run Code Online (Sandbox Code Playgroud)