3

利用 mitmproxy 保存网页中的所有图片

 2 years ago
source link: https://blog.lilydjwg.me/2015/5/30/save-images-with-mitmproxy.95114.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

利用 mitmproxy 保存网页中的所有图片

本文来自依云's Blog,转载请注明。

有个需求,保存一个网页里的所有图片。

看上去是件简单的事情,拿火狐DownThemAll 扩展下载不就好了么。

然后发现那个网页仅限移动版访问。好吧,装个 UserAgent Switcher。然后发现它是通过 JavaScript 检测 UA 的,而 UserAgent Switcher 只改了 HTTP 头里的 UA。好吧,换个 muzuiget 的 User Agent Overrider。然后发现那些图片是动态加载的,DownThemAll 根本看不到地址。后来知道「查看网页信息」的「媒体」选项卡里也是可以保存图片的,不过那里显示的图片也不全……

于是我怒了,放弃继续尝试不同的工具,决定用程序员的方式来解决问题。

我管你怎么加载的,你总归是要从网络上下载图片不是么?那我就拿个代理把你访问过的所有图片全部保存下来好了 :-)

打开 mitmproxy 文档页,发现并没有现成的保存文件的功能。但是没关系,可以写脚本。看看示例,迅速写了以下不到二十行代码:

saveimages
#!/usr/bin/mitmdump -s
from __future__ import print_function
import os
from urlparse import urlsplit
from libmproxy.protocol.http import decoded
def response(context, flow):
with decoded(flow.response):
if flow.response.headers['Content-Type'][0].startswith('image/'):
url = urlsplit(flow.request.url)
name = os.path.basename(url.path)
with open(name, 'wb') as f:
f.write(flow.response.content)
print(name, 'written')

当然这是最终结果。不过和初版差别不大,毕竟就这么点儿代码。思路也很简单,凡是经过代理的图片都存起来。有点粗暴,但是好用。

代理脚本跑起来。然后启动一个全新的 Google Chrome,一个没有任何缓存存在的实例:

google-chrome-stable --proxy-server=http://localhost:8080 --user-data-dir=new

访问目标页面,启用移动版模拟并刷新,就可以看到各种图片都被保存下来了~~


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK