Python正则表达式实现网页图片批量抓取示例

Jasper
Jasper
发布时间:2026-10-12 | 2人浏览过
原创

本文分享了一段基于Python语言的简单爬虫代码,主要利用正则表达式从指定网页中提取图片链接并批量保存至本地。代码涉及urllib库的使用、正则匹配规则定义以及文件保存逻辑,适合Python初学者参考学习基础的网络数据抓取技术。

核心功能包括:使用正则表达式进行文本匹配与替换、抓取网页内容以及将获取的图片保存至本地。

这是一段实用的Python入门代码参考。

#!/usr/bin/env python
import urllib
import re
 
x=0
def getHtml(url):
 page = urllib.urlopen(url)
 html = page.read()
 return html
 
def getImg(html):
 global x
 reg = 'alt=".+?" src="(.+?\.jpg)"'
 imgre = re.compile(reg)
 imglist = re.findall(imgre,html)
 for imgurl in imglist:
  urllib.urlretrieve(re.sub(r',\d+,\d+',',800,450',imgurl),"img/%s.jpg" % x)
  print "\n"+re.sub(r',\d+,\d+',',800,450',imgurl)+"========"+"img/%s.jpg" % x
  x+=1
 
print 'Starting...'
 
pages = range(1,9)
 
for p in pages:
 html = getHtml('http://m.lovebizhi.com/category/7655/%d/' % p)
 print "\n-------------------------page:%d-------------------------------" % p
 getImg(html)
 
print "\nDone!"

上述内容即为本文分享的完整代码示例。作者自述为Python初学者,这是其首个作品,希望能为其他学习者提供一定的帮助。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表