分析完了真实图片链接地址,下面要做的就是写代码去实现了。想直接看源代码的可以点击这里

大致思路是:获取一个页面的的html---->使用正则表达式提取出图片hash值并进行base64解码--->将解码得到的结果进行拼接替换,得到原始图片地址--->对图片地址进行请求,对返回的content进行保存--->扩展到多个页面的爬取

首先请求一个页面,我们以http://jandan.net/ooxx/page-47#comments也就是首页为例(网站会不时变动,下次可能就不是这个page值了)

def get_page_html(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
except Exception as e:
print(e)

然后使用正则表达式提取图片hash值

def get_real_img(html):
pattern = re.compile('<span class="img-hash">(.*?)</span>')
imgs_hash = re.findall(pattern, html)
for img_hash in imgs_hash:
yield base64_decode(img_hash)

使用base64解码

def base64_decode(img_hash):
img_hash = base64.b64decode(img_hash)
return img_hash

对图片进行请求

def get_img_content(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
save_img(url, response.content)
return None
except Exception as e:
print(e)

对图片进行保存

def save_img(url, content):
root = 'E://jandan/'
path = root + url.split('/')[-1]
if not os.path.exists(root):
os.mkdir(root)
if not os.path.exists(path):
with open(path, 'wb') as f:
f.write(content)
print('保存成功', url)

定义一个主函数,这里我传入了一个参数i,也就是页面号。另外加了一个睡眠,在每一次对页面进行请求获取内容前停留一段时间,防止频繁爬取被封ip。

def main(i):
start_url = 'http://jandan.net/ooxx/page-{}#comments'.format(i)
time.sleep(random.random() * random.randint(1, 10))
html = get_page_html(start_url)
for result in get_real_img(html):
url_split = result.decode('utf-8').split('/')
real_img_url = 'http://{}/{}/{}'.format(url_split[-3], 'large', url_split[-1])
get_img_content(real_img_url)

最后写一个程序入口:

if __name__ == '__main__':
start_page = 1
end_page = 47
pool = Pool()
pool.map(main, [i for i in range(start_page, end_page + 1)])

最后的最后我们看一下成果:

好了,关于煎蛋的话题就到这里。完整代码可以点击查看

最新文章

  1. C# 操作excel单元格居中
  2. 运行Shell脚本的几种方式解析
  3. [学习笔记]坚果云网盘,SVN异地代码管理
  4. redis sentinel基本命令与参数
  5. 细说.NET中的多线程 (三 使用Task)
  6. maven的入门hello world
  7. mount挂载
  8. POJ 3233 矩阵乘法
  9. grails的插件
  10. C++封装SQLite实例&amp;lt;三&amp;gt;
  11. NET Framework 4.5 五个新特性
  12. AR9531的mac地址
  13. yii2.0使用ActionForm创建表单
  14. P4语言编程快速开始 实践二
  15. Vtiger CRM 几处SQL注入漏洞分析,测试工程师可借鉴
  16. JDK1.8源码(三)——java.util.HashMap
  17. mysql常见操作语句,建表,增删改查
  18. mac电脑设置USB键盘按键方法,设置多显示屏镜像显示器的方法
  19. shell数组应用
  20. [js]ext.js探索

热门文章

  1. 【转】IBatis.Net项目数据库SqlServer迁移至Oracle
  2. WM_CTLCOLOR消息
  3. chrome 不支持12px以下字体为题的解决
  4. codeforces 1060 D
  5. 解析json方式之net.sf.json
  6. 转:Mybatis系列之集合映射
  7. 关于hadoop: command not found的问题
  8. HDU4889 Scary Path Finding Algorithm
  9. face++ API接口调用
  10. 字符设备驱动ioctl实现用户层内核层通信