python抓取豆瓣图片并自动保存示例学习

yipeiwu_com7年前Python爬虫

环境Python 2.7.6,BS4,在powershell或命令行均可运行。请确保安装了BS模块

复制代码 代码如下:

# -*- coding:utf8 -*-
# 2013.12.36 19:41 wnlo-c209
# 抓取dbmei.com的图片。

from bs4 import BeautifulSoup
import os, sys, urllib2

# 创建文件夹,昨天刚学会
path = os.getcwd()          # 获取此脚本所在目录
new_path = os.path.join(path,u'豆瓣妹子')
if not os.path.isdir(new_path):
 os.mkdir(new_path)


def page_loop(page=0):
 url = 'http://www.dbmeizi.com/?p=%s' % page
 content = urllib2.urlopen(url)

 soup = BeautifulSoup(content)

 my_girl = soup.find_all('img')  

    # 加入结束检测,写的不好....
 if my_girl ==[]:
  print u'已经全部抓取完毕'
  sys.exit(0)

 print u'开始抓取'
 for girl in my_girl:
  link = girl.get('src')
  flink = 'http://www.dbmeizi.com/' + link

  print flink
  content2 = urllib2.urlopen(flink).read()
  with open(u'豆瓣妹子'+'/'+flink[-11:],'wb') as code:   #在OSC上现学的
   code.write(content2)
 page = int(page) + 1
 print u'开始抓取下一页'
 print 'the %s page' % page
 page_loop(page)

page_loop().

相关文章

Pyspider中给爬虫伪造随机请求头的实例

Pyspider 中采用了 tornado 库来做 http 请求,在请求过程中可以添加各种参数,例如请求链接超时时间,请求传输数据超时时间,请求头等等,但是根据pyspider的原始框...

Python3网络爬虫开发实战之极验滑动验证码的识别

Python3网络爬虫开发实战之极验滑动验证码的识别

上节我们了解了图形验证码的识别,简单的图形验证码我们可以直接利用 Tesserocr 来识别,但是近几年又出现了一些新型验证码,如滑动验证码,比较有代表性的就是极验验证码,它需要拖动拼合...

Python爬虫抓取技术的一些经验

Python爬虫抓取技术的一些经验

前言 web是一个开放的平台,这也奠定了web从90年代初诞生直至今日将近30年来蓬勃的发展。然而,正所谓成也萧何败也萧何,开放的特性、搜索引擎以及简单易学的html、css技术使得we...

Python常用爬虫代码总结方便查询

beautifulsoup解析页面 from bs4 import BeautifulSoup soup = BeautifulSoup(htmltxt, "lxml") # 三种装...

Python3网络爬虫之使用User Agent和代理IP隐藏身份

Python3网络爬虫之使用User Agent和代理IP隐藏身份

本文介绍了Python3网络爬虫之使用User Agent和代理IP隐藏身份,分享给大家,具体如下: 运行平台:Windows Python版本:Python3.x IDE...