栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 网络爬虫实战:爬取百度贴吧高清原图

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 网络爬虫实战:爬取百度贴吧高清原图

前段时间受哥儿们所托,爬取贴吧某帖子里的高清图片。

事情是这样的,我哥们发现被贴吧中有好多漂亮的图片,想下载原图做壁纸,但是帖子里图片太多了,他全都要,于是想让我帮忙写个爬虫,批量下载下来。

要求只有两个:

  1. 下载原图
  2. 实现批量下载

话不多说,直接开始。

1. 分析网站

哥们提供的帖子地址: https://tieba.baidu.com/p/6516084831 。

先分析 url 组成,我们可以猜到 6516084831 是帖子的 id 。

在 勾选只看楼主,翻页 等这些操作之后,链接变成了这样 https://tieba.baidu.com/p/6516084831?see_lz=1&pn=1 ,URL 多了两个参数。基本可以确定,see_lz=1 表示只看楼主,pn=1 表示当前页数是第一页。

打开浏览器 开发者工具 ,切换到 Network 进行抓包。

发现帖子内容数据是直接渲染在 html 页面中(不是单独的数据接口),也就是说,我们只需要解析 https://tieba.baidu.com/p/6516084831?see_lz=1&pn=2 这个网页,即可获取到帖子的图片数据。

2. 反爬机制验证

用 Python 写段简单的代码,测试一下反爬机制

import requests

url = "https://tieba.baidu.com/p/6516084831?see_lz=1&pn=1"
r = requests.get(url)
print(r.text)

经测试,没什么特别的反爬机制,甚至不需要验证 User Agent 就可以直接爬到数据。

3. 提取数据

没有反爬机制,且数据就在静态网页中,那么我们直接看网页源码,解析数据。

图片在 class 为 BDE_Image 的 img 标签中,图片链接为标签的 src 属性。

import requests
from bs4 import BeautifulSoup

url = "https://tieba.baidu.com/p/6516084831?see_lz=1&pn=1"
r = requests.get(url)
html = r.text
bsObj = BeautifulSoup(html, "lxml")
imgList = bsObj.find_all("img", attrs = {"class": "BDE_Image"})
for img in imgList:
    print(img["src"])

我们通过 BeautifulSoup 库中的 find_all 函数搜索全部符合要求的 img 标签,然后取 src 属性即可。

4. 下载图片

下载图片跟爬取文本其实是一样,唯一的区别在于它的数据是二进制的。

import requests
import os

imgUrl = "http://tiebapic.baidu.com/forum/w%3D580/sign=1ecd59e749df8db1bc2e7c6c3922dddb/0f72eed3fd1f4134d5a75d01321f95cad0c85ead.jpg"
r = requests.get(imgUrl)
content = r.content
with open("image.jpg", "wb") as f:
	f.write(content)

处理网络请求的 response 时, 取 .content ,保存文件时,mode 设置为 wb ,即可。

5. 原图链接获取

不过,很快我们会发现,这样下载到的图并不是原图,而是略缩图(分辨率只有580x326 ,原图为 1920x1080 )。

经过摸索,在查看大图的页面,找到了原图的下载链接

略缩图:https://tiebapic.baidu.com/forum/w%3D580/sign=1ecd59e749df8db1bc2e7c6c3922dddb/0f72eed3fd1f4134d5a75d01321f95cad0c85ead.jpg

原图:https://tiebapic.baidu.com/forum/pic/item/0f72eed3fd1f4134d5a75d01321f95cad0c85ead.jpg

对比观察发现,在原链接的基础上稍作改动即可

“http://tiebapic.baidu.com/forum/pic/item/” + “0f72eed3fd1f4134d5a75d01321f95cad0c85ead.jpg”

6. 代码整理

通过上述的分析,我们可以实现 批量下载贴吧原图 的功能。

下面是整理后的全部源代码。

import requests
from bs4 import BeautifulSoup
import os

def fetchUrl(url):
    r = requests.get(url)
    return r.text

def parseHtml(html):
    bsObj = BeautifulSoup(html, "lxml")
    imgList = bsObj.find_all("img", attrs = {"class": "BDE_Image"})
    return imgList

def getPageNum(url):
    html = fetchUrl(url)
    bsObj = BeautifulSoup(html, "lxml")
    maxPage = bsObj.find("input", attrs={"id" : "jumpPage4"})["max-page"]
    print(maxPage)
    return int(maxPage)

def downLoadImage(imgList):
    for img in imgList:
        imgName = img['src'].split("/")[-1]
        imgUrl = "http://tiebapic.baidu.com/forum/pic/item/" + imgName
        
        if os.path.exists("高清大图/" + imgName):
            print("Skip :", imgName)
            continue
        
        picReq = requests.get(imgUrl)
        saveFile("高清大图/", imgName, picReq.content)
        print(imgName)

def saveFile(path, filename, content):
    
    if not os.path.exists(path):
        os.makedirs(path)
    
    with open(path + filename, "wb") as  f:
        f.write(content)
        
def run(tid):
    url = "https://tieba.baidu.com/p/%d?see_lz=1&pn=1" %tid
    totalNum = getPageNum(url)
    for page in range(1, totalNum + 1):
        url = "https://tieba.baidu.com/p/%d?see_lz=1&pn=%d" % (tid, page)
        html = fetchUrl(url)
        imgList = parseHtml(html)
        downLoadImage(imgList)
    
if __name__ == "__main__":
    tid = 6516084831
    run(tid)
    print("over")

如果文章中有哪里没有讲明白,或者讲解有误的地方,欢迎在评论区批评指正,或者扫描下面的二维码,加我微信,大家一起学习交流,共同进步。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/503833.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号