文章更新于:2020-04-24
注1:打包后的程序(无需python环境)下载参见:https://ww.lanzous.com/ibvwref
注2:更多爬虫案例参见:https://github.com/amnotgcs/SpiderCase

一、分析

1.1、程序流程分析

1、从用户接收一个字符串
2、判断是否存在该贴吧
3、如果存在解析总页数,并接收两个数字作为提取图片的页数
4、循环保存图片

1.2、技术分析

1、贴吧超链接为 https://tieba.baidu.com/f?ie=utf-8&kw=关键字&pn=页数x50
2、所以我们从用户接收关键字、页数即可。
3、进入贴吧后,我们可以查看源码发现每页有 50 个帖子,超连接为 https://tieba.baidu.com/p/页面ID
4、所以我们从当前页面检索出所有的页面 ID ,然后自己构造 URL 进行访问即可。
5、进入帖子页面后,我们可以发现图片的超连接都在 BDE_Image 类的 a 标签里面

6、所以我们直接提取这个 a 标签的 href 属性使用 urllib.request.urlretrieve 进行保存即可。
7、其他细节根据需要进行完善。

二、源代码

import requests
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
from os import mkdirdef setKeyword():# 构造带参 URLurl_prefix = "https://tieba.baidu.com/f?"# 确定是否存在该吧print("\n\n\t\t欢迎使用百度贴吧图片检索程序 v1.0")print("\n\n\t\t程序更新于:2020-04-24 by amnotgcs")keyword = input("\n\n\t\t请输入你要检索的贴吧名:")url = "%sid=utf-8&kw=%s"%(url_prefix, urllib.parse.quote(keyword))response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')confirmName = soup.find('a', class_ = 'card_title_fname')if confirmName:# 输出贴吧名print("\t\t已匹配:",confirmName.string.strip())else:print("\t\t该吧不存在")return NonemaxPage = soup.find('a', class_ = "last pagination-item")['href'].split("=")[-1]maxPage = int(maxPage) // 50 +1print("\n\t\t总共检索到 %d 页"%maxPage)pageNum = int(input("\t\t请输入你想要获取的开始页数:"))pageNumEnd = int(input("\t\t请输入你想要获取的结束页数:"))pageList = []if pageNumEnd - pageNum >= 0:while pageNumEnd >= pageNum:params = {'ie':'utf-8','kw': keyword,'pn': (pageNum-1)*50}url = url_prefix + urllib.parse.urlencode(params)pageList.append(url)pageNum += 1return pageListelse:return Nonedef get_html(url = ""):if not url:return None# 获取网页源码response = requests.get(url)html_doc = response.text# 调用解析函数logString = "\n" + "-"*30 + "\n下面是:%s\n"%url + "-"*30 + "\n" To_log(logString)analyseHtml(html_doc)def analyseHtml(html_doc = ""):if not html_doc:return None# 进行解析soup = BeautifulSoup(html_doc, 'html.parser')entries = soup.find_all('a')entries = soup.find_all('a', class_ = 'j_th_tit')print("\n\n帖子位置:\t\t 主题:")for item in entries:logString = "\n%s\t%s"%(item['href'],item.string)To_log(logString)entryUrl = "https://tieba.baidu.com" + item['href']# 定义图片名使用的前缀,防止覆盖pageID = item['href'].split("/")[-1]getImage(entryUrl, pageID)def getImage(url, pageID):if not url:return Nonetry:response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')except:print("\n", url, "好像出错了哦~")return None# 定位图片tags = soup.find_all('img', class_ = 'BDE_Image')if len(tags):logString = "\t\t||||||||||发现目标: %d 个图片"%len(tags)To_log(logString)else:return Noneglobal imgCountfor item in tags:try:urllib.request.urlretrieve(item['src'], r"./tiebaImg/%s_%d.jpg"%(pageID, imgCount))except:print("\n此图片保存失败", end = "")imgCount += 1def To_log(data):with open('tiebaImg/result.txt', 'a', encoding = 'utf-8')as file:file.write(data)print(data, end = "")def main():global imgCountimgCount = 0try:with open("tiebaImg/result.txt", 'w', encoding = 'utf-8')as file:file.write("程序正常开始")except:mkdir("tiebaImg")print("已经创建 tiebaImg 文件夹")pageList = setKeyword()if pageList:for page in pageList:get_html(page)print("\n", "="*60, "\n\t\t共获取 %d 图片"%imgCount)print("\t\t图片保存在程序所在目录 tiebaImg 文件夹内!")else:print("\t\t好像发现了什么奇怪了东西~")end = input("\n\t\t按回车键结束关闭窗口~")if __name__ == '__main__':main()

三、运行截图

3.1、运行截图:

3.2、运行结果:

四、Enjoy!

python 爬虫案例:爬取百度贴吧图片相关推荐

  1. 入门级别的Python爬虫代码 爬取百度上的图片

    简单讲解下python爬取百度图片的方法还有一些小坑(ps:我是搞.net的所以python只是新手讲错勿怪,注意:系统是windows下的) 首先讲下对百度图片上请求的分析:这里我引用下别人的博客, ...

  2. Python爬虫,爬取百度贴吧图片和视频文件,xpath+lxml,访问被拒的原因分析

    目录 百度贴吧图片和视频文件爬取程序 1.需求分析 2.url分析 3.Xpath分析 4.程序设计 5.坑点 百度贴吧图片和视频文件爬取程序 1.需求分析 进入百度贴吧,搜索周杰伦,进入周杰伦吧.我 ...

  3. python爬取贴吧所有帖子-Python实现的爬取百度贴吧图片功能完整示例

    本文实例讲述了Python实现的爬取百度贴吧图片功能.分享给大家供大家参考,具体如下: #coding:utf-8 import requests import urllib2 import urll ...

  4. Python爬虫之爬取绝对领域美女图片

    Python爬虫之爬取绝对领域美女图片 第一步: 导入模块: import requests from lxml import etree 第二步:定义函数: def get_url(start_ur ...

  5. python爬虫之爬取百度网盘

    爬虫之爬取百度网盘(python) #coding: utf8 """ author:haoning create time: 2015-8-15 "" ...

  6. python爬虫(13)爬取百度贴吧帖子

    爬取百度贴吧帖子 一开始只是在网上看到别人写的爬取帖子的文章,然后自己就忍不住手痒自己锻炼一下, 然后照着别人的写完,发现不太过瘾, 毕竟只是获取单个帖子的内容,感觉内容稍显单薄,然后自己重新做了修改 ...

  7. python爬虫:爬取百度小姐姐照片

    自从学会了爬虫,身体状况一天不如一天,营养都跟不上了,教大家爬取百度性感小姐姐的图片,先看一下效果. 项目流程 第一步:准备工作 工欲善其事,必先利其器 pip install requests,该模 ...

  8. Python爬虫:爬取百度图片(selenium模拟登录,详细注释)

    1.驱动下载 百度图片这种网站是动态的,即并不是网页中的内容全部存储在源代码中,而是不停地动态刷新,所以需要使用selenium模拟浏览器登录,除了安装selenium库之外,还需要针对不同地浏览器安 ...

  9. Python爬虫——关键字爬取百度图片

    在日常生活中,我们经常需要使用百度图片来搜索相关的图片资源.而如果需要大量获取特定关键字的图片资源,手动一个个下载无疑十分繁琐且费时费力.因此,本文将介绍如何通过Python爬虫技术,自动化地获取百度 ...

  10. python爬虫——批量爬取百度图片

    最近做项目,需要一些数据集,图片一张一张从网上下载太慢了,于是学了爬虫. 参考了大佬的文章:https://blog.csdn.net/qq_40774175/article/details/8127 ...

最新文章

  1. 走向.NET架构设计—第三章—分层设计,初涉架构
  2. CTFshow 反序列化 web254
  3. 复制初始化和直接初始化
  4. VHDL数字秒表的设计
  5. CCIE理论-第八篇-SD-WAN(三)+DAI(动态ARP检测)
  6. 解剖几个有点难度的C笔试题
  7. lisp 标记形心_标记-整理算法
  8. 信息学奥赛一本通C++语言——1109:开关灯
  9. 初识推荐算法---算法背景、算法概念介绍、推荐信息选取、常用推荐算法简介
  10. 大数据分析目前面临哪些问题
  11. 深度学习2-keras模型训练
  12. 用存储过程DataFactory准备测试数据
  13. 灰色系统理论的介绍与解释
  14. Some file crunching failed, see logs for details
  15. 混凝土塔吊浇筑怎么计算机械费,秒懂塔吊和施工电梯费用的摊销成本测算~
  16. 一线技术人应该关注的四种思维能力
  17. 如何编写出优秀的代码
  18. 72 ----直纹面、二次直纹面、单叶双曲面、双曲抛物面
  19. html中ch是什么单位,【CSS】ch(单位名称)
  20. centos 7修改用户名和密码

热门文章

  1. vfp制作简单计算机,VF编写简易计算器 -电脑资料
  2. ulli的csslist-style属性
  3. LayaAir Typescript安装过程详解
  4. Windows版Nessus漏洞扫描器安装与使用
  5. IOS网络第一天 - 02SDWebImage
  6. html5云彩飘过特效,Html5添加超有趣的白云飘动特效插件教程
  7. 【QML学习 01】 SystemTrayIcon 状态栏图标
  8. win下使用TensorFlow object detection训练自己模型
  9. B - 不容易系列之一
  10. 迅镭激光中标三一重工“激光2022-2023年度集采”项目!