且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python2 抓取百度贴吧图片

更新时间:2022-09-22 12:13:01

    我这里抓取的百度贴吧的地址是http://tieba.baidu.com/p/2460150866?pn=1。以下是源码,使用的是python2。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import re            #导入正则模块
import urllib        #导入url库模块
 
#抓取页面的源码
def getHtml(url):
    page = urllib.urlopen(url)       #打开指定的URL
    html = page.read()               #读取URL的内容并保存
    return html                      #函数返回读取的内容
 
#下载源码中指定的图片    
def getImg(html):
    reg = r'src="(.+?\.jpg)" pic_ext'         
    imgre = re.compile(reg)
    imglist = imgre.findall(html)
    = 0
    for imgurl in imglist:
        print(imgurl)
        #下载图片到指定的目录,并且重新命名
        urllib.urlretrieve(imgurl,r'C:\Users\Water\PycharmProjects\test\image\%s-%s.jpg' % (i,x))
        = + 1
 
#循环抓取所有的页面        
= 1
while i < 74:                #贴吧共有74页评论
    html = getHtml("http://tieba.baidu.com/p/2460150866?pn=" + str(i))
    getImg(html)
    i+=1
    print(i)


    下面是抓取的结果

Python2 抓取百度贴吧图片




     本文转自 wzlinux 51CTO博客,原文链接:http://blog.51cto.com/wzlinux/1788735,如需转载请自行联系原作者