python3 图片referer防盗链的实现方法

yipeiwu_com6年前Python基础

本篇文章主要破解referer防盗链技术

referer防盗链技术:

referer防盗链技术是服务器通过检查客户端提起的请求包内的referer字段来阻止图片下载的,如果referer字段错误,服务器会跳到另一个地址,这将导致错误的图片下载。

上面已经了解到了referer防盗链技术,下面直接上代码。

(我用的是python3,需要用到requests,html非系统包

下载方法:用python中的pip下载即可)

import urllib.request 
import requests 
import time 
import os 
import shutil 
from lxml import html 
def getPage(): 
  ''''' 
  从网站首页获取妹子的网址 
  ''' 
  fres=open('res.txt','w') 
  htm=urllib.request.urlopen('http://www.mzitu.com/') 
  out=htm.read() 
  out=html.fromstring(out) 
  urls=[] 
  for res in out.xpath('//ul[@id="pins"]/li/a/@href'): 
    urls.append(res) 
  for r in urls: 
    fres.write(r) 
    fres.write('\n\r') 
  fres.close() 
  return urls 
def getPiclink(url): 
  ''''' 
  获取一个妹子的标题和她的所有图片地址 
  ''' 
  i_headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0'} 
  sel=urllib.request.Request(url, headers=i_headers) 
  #使用代理浏览器访问网站 
  sel.add_header('Referer', 'http://www.mzitu.com/') 
  #将referer字段添加到请求包里 
  sel=urllib.request.urlopen(sel).read() 
  sel=html.fromstring(sel) 
  total=sel.xpath('//div[@class="pagenavi"]/a[last()-1]/span/text()')[0] 
  title=sel.xpath('//h2[@class="main-title"]/text()')[0] 
  jpglist=[] 
  for i in range(int(total)): 
    link='{}/{}'.format(url, i+1) 
    s=html.fromstring(urllib.request.urlopen(link).read()) 
    jpg=s.xpath('//div[@class="main-image"]/p/a/img/@src')[0] 
    jpglist.append(jpg) 
  return title,jpglist 
def downloadJpg(title,piclist,link): 
  ''''' 
  下载getPiclink()获取到的妹子的图片 
  ''' 
  k=1 
  count=len(piclist) 
  dirname=u"[%sP]%s" %(str(count),title) 
  if os.path.exists(dirname): 
    shutil.rmtree(dirname) 
  os.mkdir(dirname) 
  i_header={} 
  i_header['Referer']=link 
  #将getPiclink()获取到的妹子的首页网址作为referer字段的值 
  for i in piclist: 
    filename='%s/%s/%s.jpg' %(os.path.abspath('.'),dirname, k) 
    with open(filename,'wb') as jpg: 
      jpg.write(requests.get(i, headers=i_header).content) 
    #将referer字段添加到请求包里并下载图片 
      time.sleep(0.5) 
    k+=1 
if __name__=='__main__': 
  for link in getPage(): 
    title,pic=getPiclink(link) 
    downloadJpg(title,pic,link) 
  print('OK!') 

另外给大家推荐一个很好的抓包工具wireshark,我就是通过wirshark抓包分析后得到的referer信息。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

如何更优雅地写python代码

前言 Python 这门语言最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。但有时候我们写代码,特别是 Python 初学者,往往还是按照其它语言的思维习惯来写...

Python 3.x基于Xml数据的Http请求方法

Python 3.x基于Xml数据的Http请求方法

1. 前言 由于公司的一个项目是基于B/S架构与WEB服务通信,使用XML数据作为通信数据,在添加新功能时,WEB端与客户端分别由不同的部门负责,所以在WEB端功能实现过程中,需要自己发...

Python类的基础入门知识

复制代码 代码如下:class Account(object): "一个简单的类" account_type="Basic" def __init__(self,name,balance...

一篇文章入门Python生态系统(Python新手入门指导)

一篇文章入门Python生态系统(Python新手入门指导)

译者按:原文写于2011年末,虽然文中关于Python 3的一些说法可以说已经不成立了,但是作为一篇面向从其他语言转型到Python的程序员来说,本文对Python的生态系统还是做了较为...

Python模拟随机游走图形效果示例

Python模拟随机游走图形效果示例

本文实例讲述了Python模拟随机游走图形效果。分享给大家供大家参考,具体如下: 在python中,可以利用数组操作来模拟随机游走。 下面是一个单一的200步随机游走的例子,从0开始,步...