正在学习用python写爬虫,在网上看了一些博客,自己也尝试了一下。
本脚本的功能:对一个帖子进行翻页并下载正文中的图片
【源码】
#!/usr/bin/python
#coding:utf-8
import re
import urllib
import urllib2
def gethtml(url):
page=urllib.urlopen(url)
html=page.read()
return html
def getImg(html,y):
reg=r'img class="BDE_Image" src="(.*?\.jpg)"'
imgre=re.compile(reg)
imglist=re.findall(imgre,html)
#print imglist
x=0
for imgurl in imglist:
path="C:\Users\John\Desktop\workspace1\GetImg\src\img\%s_%s.jpg"% (y,x)
data=urllib.urlopen(imgurl).read()
f=file(path,"wb")
f.write(data)
f.close()
x+=1
print "ok"
p=1
while(p<31):
geturl="http://tieba.baidu.com/p/3831653735?pn=%s"% p
print "正在下载第%s页图片..."%p
html=gethtml(geturl)
getImg(html,p)
p+=1
print "下载结束"