基于urllib2库 和python 语言的网页图片爬虫

本文介绍了一个简单的Python爬虫脚本,用于从指定网站抓取图片资源。通过使用urllib2和re模块,该脚本能够解析网页源代码,识别并下载jpg格式的图片。文章适合初学者,详细展示了如何设置User-Agent,创建Request对象,以及如何使用正则表达式匹配图片链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 我也是刚刚学会,面向小白。主要是记录一下怎么写的。

 

 

# -*- coding: utf-8 -*-
import urllib2
import re
import urllib
 
if __name__ == "__main__":
    url = 'http://history.bnu.edu.cn/'
    # 写入 User Agent 信息    
    head = {}  
    head['User-Agent'] = 'Mozilla/5.0 **********你的user agent'
    #创建 Request 对象
    req = urllib2.Request(url, headers=head)
    #传入创建好的 Request 对象
    response = urllib2.urlopen(req)
    #读取响应信息并解码
    data = response.read().decode('utf-8')
    #构建正则表达式 
    reg = 'src="(.+?\.jpg)" '   
    #读取html中包含正则表达式的数据
    imgList = re.findall(reg,data)  
    n = 1
    for each in imgList:
        print(each)
        try:
            imgurl = 'http://history.bnu.edu.cn/'+each            
            urllib.urlretrieve(imgurl,'D:\information-retrieval\pictures\\%s.jpg' %n)
            #以下方法解决一些较大图片无法完整下载的问题
            #filename = 'D:\information-retrieval\pictures\\%s.jpg' %n
            #conn = urllib2.urlopen(imgurl)
            #output = open(filename, 'wb') #binary flag needed for Windows
            #output.write(conn.read())
            #output.close()
        except Exception as e:
            print(e)
        finally:
            print(each)
        n+=1
    #输出结果
    #print(data)
    #print(imgList)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值