用Python写的图片蜘蛛人
写了个图片蜘蛛人玩玩,抓了几个网页试试,感觉不不错。核心的代码可能20行也不到,简洁明了,嘻嘻。废话少说,翠花,上代码~~
#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()
相关文档:
# 直接插入排序
def InsertSort(mylist):
size = len(mylist)
i = 1
for i in range(1, size):
if mylist[i] < mylist[i - 1]:
tmp = mylist[i]
j = i - 1
mylist[j + 1] = mylist[j]
j = j - 1
while j > ......
我的环境是:Linux version 2.4.21-4.EL
(bhcompile@daffy.perf.redhat.com) (gcc version 3.2.3 20030502 (Red Hat
Linux 3.2.3-20)) #1 Fri Oct 3 18:13:58 EDT 2003 + Python2.6.4
本文结合我安装时候的问题,总结而成
用户目录如/home/liuguanyu/ , 保证用户有root权限
1,看看有没有安装
&nbs ......
参考链接:http://www.woodpecker.org.cn/diveintopython/functional_programming/dynamic_import.html
一 动态导入模块
Python的import不能接受变量,所以应该用 __import__函数来动态导入。
如下的代码无法正常导入模块
modules = ['OpenSSL', 'Crypto', 'MySQLdb', 'sqlite3', 'zope.interface', 'pyasn1', 'twisted ......
1. Building an Application with PyGTK and Glade
2. Creating a GUI using PyGTK and Glade
3. A Beginner's Guide to Using pyGTK and Glade
4. Is there a walkthrough on getting PyGTK2 and libglade2 to work on win32 ......
只需要在文件中import与你写的文件的文件名一致的模块名即可,这时python会为你创建一个pyc文件的。
即,如果你已经写了一个名为ssss.py的文件,而现在你需要在名为aaaa.py的文件中使用ssss.py中定义的方法,那么你只需要在aaaa.py中加入import ssss,然后你就可以在aaaa.py中使用ssss.py中的方法(当然方法前需要加模块名 ......