Python爬虫获取图片并下载保存至本地的实例

yipeiwu_com5年前Python爬虫

1、抓取煎蛋网上的图片。

2、代码如下:

import urllib.request
import os
#to open the url
def url_open(url):
 req=urllib.request.Request(url)
 req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0')
 response=urllib.request.urlopen(url)
 html=response.read()
 return html
#to get the num of page like 1,2,3,4...
def get_page(url):
 html=url_open(url).decode('utf-8')
 a=html.find('current-comment-page')+23 #add the 23 offset th arrive at the [2356]
 b=html.find(']',a)
 #print(html[a:b])
 return html[a:b]
#find the url of imgs and return the url of arr
def find_imgs(url):
 html=url_open(url).decode('utf-8')
 img_addrs=[]
 a=html.find('img src=')
 while a!=-1:
  b=html.find('.jpg',a,a+255) # if false : return -1
  if b!=-1:
   img_addrs.append('http:'+html[a+9:b+4])
  else:
   b=a+9
  a=html.find('img src=',b)
 #print(img_addrs)  
 return img_addrs
  #print('http:'+each)
  
#save the imgs 
def save_imgs(folder,img_addrs):
 for each in img_addrs:
  filename=each.split('/')[-1] #get the last member of arr,that is the name
  with open(filename,'wb') as f:
   img = url_open(each)
   f.write(img)
 
def download_mm(folder='mm',pages=10):
 os.mkdir(folder)
 os.chdir(folder)
 url='http://jandan.net/ooxx/'
 page_num=int(get_page(url))
 
 for i in range(pages):
  page_num -= i
  page_url = url + 'page-' + str(page_num) + '#comments'
  img_addrs=find_imgs(page_url)
  save_imgs(folder,img_addrs)
  
if __name__ == '__main__':
 download_mm()

以上这篇Python爬虫获取图片并下载保存至本地的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python爬虫框架talonspider简单介绍

1.为什么写这个? 一些简单的页面,无需用比较大的框架来进行爬取,自己纯手写又比较麻烦 因此针对这个需求写了talonspider: •1.针对单页面的item提取 - 具...

python3制作捧腹网段子页爬虫

python3制作捧腹网段子页爬虫

0x01 春节闲着没事(是有多闲),就写了个简单的程序,来爬点笑话看,顺带记录下写程序的过程。第一次接触爬虫是看了这么一个帖子,一个逗逼,爬取煎蛋网上妹子的照片,简直不要太方便。于是乎就...

详解用python写网络爬虫-爬取新浪微博评论

新浪微博需要登录才能爬取,这里使用m.weibo.cn这个移动端网站即可实现简化操作,用这个访问可以直接得到的微博id。 分析新浪微博的评论获取方式得知,其采用动态加载。所以使用json...

python3爬取数据至mysql的方法

本文实例为大家分享了python3爬取数据至mysql的具体代码,供大家参考,具体内容如下 直接贴代码 #!/usr/local/bin/python3.5 # -*- codin...

Python爬虫实战之12306抢票开源

Python爬虫实战之12306抢票开源

今天就和大家一起来讨论一下python实现12306余票查询(pycharm+python3.7),一起来感受一下python爬虫的简单实践 我们说先在浏览器中打开开发者工具(F12),...