1、首先分析百度贴吧下的url与源码

例如:https://tieba.baidu.com/p/5185002863?pn=1

Python爬虫实战一之爬取百度贴吧中图片

Python爬虫实战一之爬取百度贴吧中图片


url:https://tieba.baidu.com/p/5185002863?pn=1

其中pn=1中的1是一个变量:当前的第几页

图片的源代码:提前部分,如:src="https://imgsa.baidu.com/forum/w%3D580/sign=5f3f2a90753e6709be0045f70bc69fb8/61310a55b319ebc44ffca02e8826cffc1f171685.jpg",这样的话,需要提取这个图标的url才能找到这个图片,然后存储起来

通过正则匹配:src=\"(https://[\w\=\/\%\.]+\.jpg)\"

2、源代码如下

#encoding:utf-8

import urllib
import urllib2
import re

if __name__ == '__main__':
    #总页数
    pagenum=6
    #贴吧的url
    url="https://tieba.baidu.com/p/5185002863?pn="
    #计数器或者图片记录个数
    x=0
    for i in range(1,pagenum+1):
        #获取url的请求
        request=urllib2.Request(url+str(i))
        #获取url的响应
        response=urllib2.urlopen(request)
        #获取url对应的源代码html
        html=response.read()
        #从html源码中提取想要图片对应的正则表达式
        reg="src=\"(https://[\w\=\/\%\.]+\.jpg)\""
        imgre=re.compile(reg)
        imglist=re.findall(imgre,html)
        for img in imglist:
            print img
            urllib.urlretrieve(img, 'E:\pic\%s.jpg'% x)

            x+=1

3、执行结果

Python爬虫实战一之爬取百度贴吧中图片

相关文章: