根据输入的贴吧地址,爬取想要该贴吧的图片,保存到本地文件夹,仅供参考:
#!/usr/bin/python
#_*_coding:utf-8_*_
import urllib
import urllib2
import re
import os
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
#下载图片
class GetPic:
#页面初始化
def __init__(self,baseUrl,seelz):
#base链接地址
self.baseURL = baseUrl
#是否只看楼主
self.seeLZ = '?seelz=' + str(seelz)
#self.tool = tool.Tool()
#获取页面内容
def getPage(self,page):
try:
url = self.baseURL + self.seeLZ + '&pn=' + str(page)
request = urllib2.Request(url)
response = urllib2.urlopen(request)
html = response.read().decode('utf-8')
#print html
return html
#链接报错的原因
except urllib2.URLError, e:
if hasattr(e,"reason"):
print u'链接百度贴吧失败,错误原因:',e.reason
return None
#获取帖子一共有多少页
def getPageNum(self,page):
page = self.getPage(1)
pattern = re.compile('<li class="l_reply_num.*?</span>.*?<span.*?>(.*?)</span>',re.S)
result = re.search(pattern,page)
if result:
#输出页码数
#print result.group(1)
pagenum = result.group(1).strip()
#print result.group(1)
return pagenum
else:
print None
#获取页面的图片
def getPic(self,page):
html = self.getPage(page)
#正则匹配图片的地址
reg = r'<img class="BDE_Image".*?src="(.*?)".*?>'
pattern = re.compile(reg)
items = re.findall(pattern,html)
return items
def savePic(self,page):
#pageNum = self.getPageNum(1)
items = self.getPic(page)
x = 0
for item in items:
print item
#根据实际保存图片的地址进行修改
urllib.urlretrieve(item,'D:\learn\python-bqb\%s-%s.jpg' % (page,x))
x += 1
def Start(self):
#indexPage = self.getPage(1)
pageNum = self.getPageNum(1)
if pageNum == None:
print "URL已失效,请重试"
return
try:
print "该帖子共有" + str(pageNum) + "页"
for i in range(1,int(pageNum) + 1):
print "正在写入第" + str(i) + "页数据"
#self.getPage(i)
#self.getPic(i)
self.savePic(i)
except IOError,e:
print "写入异常,原因" + e.message
finally:
print "写入任务完成"
print u"请输入帖子的代号"
baseURL = 'http://tieba.baidu.com/p/' + str(raw_input(u'http://tieba.baidu.com/p/'))
seeLZ = raw_input("是否只获取楼主发表的图片,是输入1,否输入0\n")
bdtp = GetPic(baseURL,seeLZ)
bdtp.Start()
'''
#创建目录保存图片
def mkdir(self,path):
path = path.strip()
#判断路径是否存在
#存在 返回True
#不存在 返回False
isExists = os.path.exists(path)
#判断结果
if not isExists:
#如果不存在则创建目录
print u"新创建了目录名为:" + path
#创建目录操作函数
os.makedirs(path)
return True
else:
#如果目录已存在不创建,提示目录已存在
print u"目录" + path + "已存在"
return False
#保存图片
def savePic(html,items):
x = 0
for item in items:
filename = item + '.jpg'
while open(filename,'wb') as fp:
img = getPic(html)
fp.write(img)
'''