Python3+urllib爬取海量精美图片

下载Python3:https://www.python.org/

安装的时候记得勾选添加环境变量

本代码参考了网上的一些教程,我又根据自己的理解简化了代码:

import re,os,time
import urllib.request

os.mkdir('mm')
os.chdir('mm')

#请求头
head={}
head['User-Agent']='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'

#设置网站起始页码
cou=2350
while True:
    strcou=str(cou)
    cou=cou+1
    #网站首页地址
    url2='http://jandan.net/ooxx/page-'+strcou+'#comments'
    a=urllib.request.Request(url2,data=None,headers=head)
    res=urllib.request.urlopen(a).read().decode('utf-8')
    #正则表达式匹配网址
    a=re.findall(r'//wx+.+?.jpg',res)
    #去掉列表中重复的网站点
    ll=list(set(a))
    #计算列表中有多少个网站
    b=len(ll)
    c=b-1
    while True:
        #这个是图片地址
        url='http:'+a[c]
        resp=urllib.request.Request(url,data=None,headers=head)
        res=urllib.request.urlopen(resp).read()
        #保存图片
        with open(str(int(time.time()))+'.jpg','wb') as f:
            f.write(res)
        c-=1
        if c==0:
            break

导入必要的模块

import re,os,random
import urllib.request

在当前工作目录创建文件夹,名字为mm

os.mkdir('mm')
os.chdir('mm')

#请求头,如果不加请求头的话,服务器就会判定这是一个非人类访问。访问一些网站将会被服务器拒绝
 
head={} head['User-Agent']='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' 
如下就是不加请求头的报错:

#设置网站起始页码  网站原始首页http://jandan.net/ooxx/page-2379#comments
 
2379就是包含在网站里的页码,改变这个数字,浏览器显示的图片就不一样了,就是利用这一点,就可以每一次循环改变网站的地址
获取不同的图片
cou=2379
第一个循环代表获取不同的图片
while True:
    #cou是数字类型,需要把它转换成字符类型填写在网址中
    strcou=str(cou)
    #每一次循环访问页面,就在原来的页码上加1
    cou=cou+1
    #网站首页地址
   

    url2='http://jandan.net/ooxx/page-'+strcou+'#comments'
    a=urllib.request.Request(url2,data=None,headers=head)
    res=urllib.request.urlopen(a).read().decode('utf-8')
    #正则表达式匹配网址,获取该页面所有以//wx开头以.jpg结尾的url,这个url就是图片的地址
    a=re.findall(r'//wx+.+?.jpg',res)
    #去掉列表中重复的网站点
    ll=list(set(a))
    #计算列表中有多少个网站
    b=len(ll)
    c=b-1
第二个循环代表获取页面的url:
    while True:
        #随机生成两个数字用于图片命名
        cc=str(random.randint(1,200))
        dd=str(random.randint(1,200))
        #这个是图片地址
        url='http:'+a[c]
        resp=urllib.request.Request(url,data=None,headers=head)
        res=urllib.request.urlopen(resp).read()
        #保存图片
        with open(cc+dd+'.jpg','wb') as f:
            f.write(res)
        c-=1
        if c==0:
            break

爬取的图片:

猜你喜欢

转载自blog.csdn.net/xiaojiawen/article/details/60470739
今日推荐