python小爬虫【1】

爬取百度贴吧的图片

分析贴吧源代码,图片所在位置是:<img class="BDE_Image" src=“。。。。。。。.jpg” pic_ext。。。。。

所以正则匹配是:

r'BDE_Image" src="(.+?\.jpg)" pic_ext'

(注:?表示懒惰匹配,如果不加?会造成匹配到一个"BDE_Image" src=“起始到网页最后一个pic_ext结束的一个串。

           ()表示所要提取的字符串,即。。。。.jpg

代码如下:

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

import os
import re
import urllib

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

def getImages(html):
    reg = r'BDE_Image" src="(.+?\.jpg)" pic_ext'
    imgre =  re.compile(reg)
    imgList = imgre.findall(html)
    print 'We have got %d pictures' % len(imgList)
    path = './download'
    x = 0
    for imgurl in imgList:
        FileName = os.path.join(path, '%s.jpg' % (x+1))
        urllib.urlretrieve(imgurl,FileName)
        print '%s.jpg is done.' % (x+1)
        x = x + 1

if __name__ == '__main__':
    url = raw_input('input the URL:>')
    html = getHtml(url)
    getImages(html)

还是最为基础的功能。

转载于:https://www.cnblogs.com/buptmuye/p/3462844.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值