代码(没有优化):
#2015年9月19日 10:16:30
#爬取贴吧图
#by imekaku.com
#贴吧爬虫tiebav1.0
import urllib.request
import re
import os
import sys
#创建目录,并且判断是否存在
title = input('请输入您要爬取哪一话(如:151):')
dirnow = './' + title
if(os.path.exists(dirnow)):
dirError = input('您输入的目录已经存在,请重新运行程序')
sys.exit()
url = input('请输入您需要爬取的百度贴吧的地址:')
print('图片爬取中,请稍后..')
#创建目录
os.mkdir(title)
os.chdir(title)
def openUrl(url):
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')
return html
html = openUrl(url)
p = re.compile('''class="BDE_Image.*?src="(.*?)"''')
items = p.findall(html)
count = '1'#给图片取名,标序号
for item in items:
filename = title + '-' + str(count) + '.jpg'
with open(filename, 'wb') as f:
img = urllib.request.urlopen(item).read()
f.write(img)
count = int(count) + 1
喜欢 (0)or分享 (0)