import requests
import re
import os
class Tiba_pic:
def __init__(self):
self.url="https://tieba.baidu.com/f?"
self.headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"}
def change_page(self): #进行换页的函数
self.files=".\百度贴吧" #创建一个文件路径 用于保存图片
if not os.path.exists(self.files): #检测当前路径下是否存在此文件夹
os.mkdir(self.files) #创建文件夹
name=input("请输入要抓取的贴吧名称:")
begin=int(input("请输入抓取的起始页:"))
end=int(input("请输入抓取的终止页:"))
for page in range(begin,end+1):
#构造请求的参数字典
params={
"kw":name, #请求贴吧名称
"pn":str((page-1)*50) #获取页数范围
}
res=requests.get(self.url,headers=self.headers,params=params)
res.encoding="utf-8"
html = res.text
self.get_t_url(html) #调用获取帖子链接的函数
def get_t_url(self,html): #获取所有帖子链接的函数
p = re.compile('<div class="threadlist_title pull_left j_th_tit ".*?href="(.*?)"', re.S)
t_list = re.findall(p, html)
for t in t_list:
t_url="https://tieba.baidu.com"+t #拼接帖子的完整链接
res=requests.get(t_url,headers=self.headers)
res.encoding="utf-8"
html=res.text
self.get_pic_url(html) #调用获取图片链接的函数
def get_pic_url(self,html): #获取图片链接的函数
p1 = re.compile('<img class="BDE_Image".*?src="(.*?)"', re.S)
pic_list = re.findall(p1, html)
if pic_list!=[]: #判断帖子中是否有图片链接
for i in pic_list:
filename=i[-10:] #以图片链接的后10位作为图片名称
self.save_pic(i,filename) #调用保存图片的函数
def save_pic(self,pic_url,filename): #保存图片的函数
filename=self.files+"\\"+filename #将图片下载路径设置为文件夹内
res=requests.get(pic_url,headers=self.headers)
res.encoding="utf-8"
html=res.content
with open(filename, "wb") as f:
f.write(html)
print(filename, "下载成功!")
tieba=Tiba_pic()
tieba.change_page()
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
贴吧爬取.rar (10个子文件)
贴吧爬取
第2.html 2KB
.idea
workspace.xml 12KB
misc.xml 294B
inspectionProfiles
profiles_settings.xml 174B
modules.xml 283B
贴吧爬取.iml 324B
百度贴吧
tieba.py 2KB
第1.html 2KB
t.py 324B
baidu_pic.py 2KB
共 10 条
- 1
资源评论
浮生若梦777
- 粉丝: 508
- 资源: 3
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功