python自动下载图片_python简易爬虫来实现自动图片下载

菜鸟新人刚刚入住博客园,先发个之前写的简易爬虫的实现吧,水平有限请轻喷。

估计利用python实现爬虫的程序网上已经有太多了,不过新人用来练手学习python确实是个不错的选择。本人借鉴网上的部分实现加以改造实现网页图片地址提取和下载。首先找到你感兴趣的网页,以bbs论坛为例,查看网页的源代码发现图片下载的链接地址类似如下:

img-fa6533d1b03dee194f0636a69eea5c64.jpg

所以找到了属性href值就可以解析出我们的下载地址了(要加入当前url前缀才是绝对地址呦)。用python写个处理网页的函数可以这样

1 defgetImg(html,page):2 reg = r'attachment.php?.+"'

3 imgre =re.compile(reg)4 imglist =imgre.findall(html)5 x =06 importos7 path = "d:\\picture\\"

8 title = "%s\\" %page9 new_path =os.path.join(path, title)10 if notos.path.isdir(new_path):11 os.makedirs(new_path)12

13 for imgurl inimglist:14 imgurl=imgurl[:imgurl.find('"')]15 imgurl=imgurl.rstrip('"')16 printimgurl17 imgurl="http://xxxxxx/"+imgurl18 f =urllib2.urlopen(imgurl)19 with open(new_path+"%s.gif" % x, "wb") as code:20 code.write(f.read())21 x = x + 1

以上用的是最简单的正则匹配,将解析后的图片下载保存到D盘picture目录。

有时候论坛是要登录的,所以处理模拟登录这块根据你所处理的网站会稍许不同,实现模拟登陆功能大部分是提交登陆表单。这里就要用到python发送登陆表单请求消息了,利用httpfox插件获取登陆的post信息,

1 ef login(weburl,username,password,page):2 cookie_support=urllib2.HTTPCookieProcessor(cookielib.CookieJar())3 opener =urllib2.build_opener(cookie_support, urllib2.HTTPHandler)4 urllib2.install_opener(opener)5 postdata=urllib.urlencode({6 'loginfield':'username',7 'formhash':gethash(weburl),8 'password':password,9 'username':username,10 'questionid':0,11 'answer':'',12 'loginsubmit':'true'})13 postdata=postdata.encode(encoding='UTF8')14 header = {'User-Agent':'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)'}15 posturl=weburl16 req =urllib2.Request(posturl,postdata)17 result =urllib2.urlopen(req).read()18 Url="http://xxxxxxxxxx/viewthread.php?tid=14943&extra=page%3D1&page="

19 Url=Url+("%s" %page)20 result=getHtml(Url);21 return result

View Code

到这边都是比较简单实现的,稍微麻烦点的是请求表单中postdata中需要获取随机的hash值,因此首先要解析出你登陆界面中的那个formhash,这个用re模块简单解析处理一下就ok了

1 defgethash(url):2 page =urllib2.urlopen(url)3 html =page.read()4 reg = r'name="formhash" value=".+"'

5 hashre =re.compile(reg)6 hashvalue=hashre.findall(html)7 pos=(hashvalue[0]).index('value=')8 hash=(hashvalue[0])[pos+6:]9 print hash.strip('"')10 return hash.strip('"')

View Code

,以上就是用到的大部分函数了,当然解析网页还有更多的好用的模块比如beautifulsoup等等,简单研究一下应该就能实现一个简易的爬虫程序了。

第一次在园子写东西,写的比较乱,以后改进。接下来准备介绍一下如何用python实现一个RSS阅读器。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值