欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用Python写的图片蜘蛛人代码

程序员文章站 2024-03-30 23:48:51
复制代码 代码如下:#coding=utf-8 import os import sys import re import urllib url_reg = re.comp...

复制代码 代码如下:

#coding=utf-8

import os
import sys
import re
import urllib

url_reg = re.compile(r'(http://[^///]+)', re.i)
img_reg = re.compile(r'<img[^>]*?src=([/'"])([^/1]*?)/1', re.i)

def download(dir, url):
'''下载网页中的图片

@dir 保存到本地的路径
@url 网页url
'''
global url_reg, img_reg

m = url_reg.match(url)
if not m:
print '[error]invalid url: ', url
return
host = m.group(1)

if not os.path.isdir(dir):
os.mkdir(dir)

# 获取html,提取图片url
html = urllib.urlopen(url).read()
imgs = [item[1].lower() for item in img_reg.findall(html)]
f = lambda path: path if path.startswith('http://') else /
host + path if path.startswith('/') else url + '/' + path
imgs = list(set(map(f, imgs)))
print '[info]find %d images.' % len(imgs)

# 下载图片
for idx, img in enumerate(imgs):
name = img.split('/')[-1]
path = os.path.join(dir, name)
try:
print '[info]download(%d): %s'% (idx + 1, img)
urllib.urlretrieve(img, path)
except:
print "[error]cant't download(%d): %s" % (idx + 1, img)

def main():
if len(sys.argv) != 3:
print 'invalid argument count.'
return
dir, url = sys.argv[1:]
download(dir, url)

if __name__ == '__main__':
# download('d://imgs', 'http://www.163.com')
main()