(58)-- 用正则层层爬取图片

# 用正则层层爬取图片

from urllib import request
import re

base_url = 'http://www.mmonly.cc/wmtp/fjtp/list_21_{}.html'

def download(pic_url):
    print('downloading...%s' % pic_url)
    fname = pic_url.split('/')[-1]
    request.urlretrieve(pic_url,'images/' + fname)

def getPage():

    for i in range(1,73):
        fullurl = base_url.format(i)
        response = request.urlopen(fullurl)
        html = response.read().decode('gb2312','ignore')
        url_pat = re.compile(r'<div class="btns" > <a class="img_album_btn" href="http://www.mmonly.cc/wmtp/fjtp/(.*?)"', re.S)
        res = url_pat.findall(html)

        for url in res:
            new_url = 'http://www.mmonly.cc/wmtp/fjtp/' + url
            response = request.urlopen(new_url)
            html = response.read().decode('gb2312','ignore')
            img_pat = re.compile(r'<img alt=".*?" src="(.*?)"')
            res = img_pat.findall(html)

            for pic_url in res:
                download(pic_url)


if __name__ == '__main__':
    getPage()




# 爬取部分结果如下(记得在同级目录上先建立一个images文件夹)

C:\Users\cz\AppData\Local\Programs\Python\Python35\python.exe E:/Python/python高阶/43.py
downloading...http://t1.mmonly.cc/uploads/tu/201703/54/131.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/54/151.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/54/141.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/54/121.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/54/111.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201608/154/oamsep4zucp.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201608/155/dj1ju5h0ihi.jpg
downloading...http://t1.mmonly.cc/uploads/allimg/20150727/pnh1hrge3tn.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/37/151.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/37/141.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/37/131.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/37/121.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/37/13b1OOOPICe1.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/30/151.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/30/141.jpg
downloading...http://t1.mmonly.cc/uploads/tu/201703/30/131.jpg

Process finished with exit code 1

兄弟连学python


Python学习交流、资源共享群:563626388 QQ


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值