shell教程 爬取百度贴吧图片


一.简介

shell使用curl可来爬取一些图片,虽然没有实际作用,但在学习中理解命令和网页还是很不错的。

二.详解

1.首先在百度贴吧输入一个吧名,随便都可以,主要看浏览器地址
file

地址是这个--->https://tieba.baidu.com/f?kw=领域少女
也就是说kw=前面不变,变的是后面的名称

2.接下来点进一个帖子
file

从中可以看到点击完的地址--->https://tieba.baidu.com/p/5649084634
多点击几个,看到/p/前面的不变,变得是后面的数字

3.进到linux中,将网页的html代码保存
curl https://tieba.baidu.com/f?kw=领域少女 > a.txt
grep查找一下刚才的数字,因为帖子的连接肯定保存在首页html中,你点击才能跳转到帖子的
grep "5649084634" a.txt

grep的结果可以看出都是如下结构---><a rel="noreferrer" href=*

file

4.用正则找出这些帖子的链接
因为/p/中/是匹配字符,所以要用\屏蔽效果
grep '<a rel="noreferrer" href="\/p\/*' a.txt |awk '{print $3}' |awk -F'"' '{print $2}' | awk -F'/' '{print $3}'

file

5.分析单个帖子
在网页找到图片右键,复制图片地址
file

它的地址是这个--->https://imgsa.baidu.com/forum/w%3D580/sign=5d36f7885b2c11dfded1bf2b53266255/685086eece1b9d16c215aa0affdeb48f8d546425.jpg

到linux下载帖子的html代码
curl https://tieba.baidu.com/p/5649084634 > a.txt
查找图片的格式
grep 'https://imgsa.baidu.com/forum/w%3D580/sign=5d36f7885b2c11dfded1bf2b53266255/685086eece1b9d16c215aa0affdeb48f8d546425.jpg' a.txt

6.筛选链接
查找出图片地址
egrep -o '<img class="BDE_Image" src=[^>]*>' a.txt |awk -F'"' '{print $4}'

file

7.写脚本批量下载(当前只写大致)
vim pa-tieba.sh

#!/bin/bash
#爬取百度贴吧图片脚本,当前只限第一页所有帖子图片

#处理主页
zhuye() {
    for i in `grep '<a rel="noreferrer"  href="\/p\/*' $1 |awk '{print $3}' |awk -F'"' '{print $2}' | awk -F'/' '{print $3}'`
    do
        tiezi $i linshi1.txt #挨个下载帖子中图片
	sleep 1 #缓解下载压力
    done
}

#处理帖子
tiezi() {
    curl https://tieba.baidu.com/p/$1 > $2
    for i in `egrep -o '<img class="BDE_Image" src=[^>]*>' $2 |awk -F'"' '{print $4}'`
    do
      wget $i  
    done
}

if [ $# -eq 1 ];then
    [ -d tupian ] || mkdir tupian
    cd tupian
    curl https://tieba.baidu.com/f?kw=$1 > linshi.txt
    zhuye linshi.txt
    echo "下载完成"
else
    echo "xx.sh 领域少女"
fi


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM