怎样用Python 写一个爬图片的程序?

在V2EX上看到一个问题"怎样用Python 写一个爬图片的程序?"http://www.v2ex.com/t/61686#reply18点击打开链接

需求:我很喜欢杉本有美大妹子,想从贴吧抓取她的全部写真照,这样就不用一张张右键,我该怎么一步步做呢?

http://tieba.baidu.com/p/2166231880

Ubuntu12.04系统:

1.安装:sudo easy_install-2.7 -U pip
2.安装:sudo pip-2.7 install requests
3.安装:sudo easy_install lxml
  第3步会报错:
    ERROR: /bin/sh: 1: xslt-config: not found
    ** make sure the development packages of libxml2 and libxslt are installed **
  解决方法:google search "ubuntu install python lxml"
     安装:sudo apt-get install python-lxml  


代码:https://gist.github.com/anonymous/5066411点击打开链接

downloadimages.py

import requests
import lxml.html
 
page = requests.get('http://tieba.baidu.com/p/2166231880').text
doc = lxml.html.document_fromstring(page)
for idx, el in enumerate(doc.cssselect('img.BDE_Image')):
    with open('%03d.jpg' % idx, 'wb') as f:
        f.write(requests.get(el.attrib['src']).content)

执行:

python downloadimages.py 

去目录里看看妹子图片吧....

------------------------------------------------------------------------------

Windows下运行该代码:

1、安装相关包(注意版本号):cmd 下 easy_install lxml==2.3 




2、Windows二进制安装(也可以采用此方法):http://www.lfd.uci.edu/~gohlke/pythonlibs/  点击打开

链接




3、运行 downloadimages.py,图片就下载下来了。-:)


----------------------------------------------------------------------------------


使用urllib和re库也可以解决问题:

代码如下:

#! /usr/bin/env python
#coding:utf-8

import urllib,re

def get_html(url):
    page = urllib.urlopen(url)
    html = page.read()
    return html

def get_img(html):
    reg = r'src="(.*?\.jpg)" bdwater='
    imgre = re.compile(reg)
    imglist = re.findall(imgre, html)
    i = 0
    for imgurl in imglist:
        urllib.urlretrieve(imgurl, '%s.jpg'%i)
        i+=1
html = get_html('http://tieba.baidu.com/p/2166231880')
print get_img(html)


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值