一.簡介
shell使用curl可來爬取一些圖片,雖然沒有實際作用,但在學習中理解命令和網頁還是很不錯的。
二.詳解
1.首先在百度貼吧輸入一個吧名,隨便都可以,主要看瀏覽器地址
地址是這個--->https://tieba.baidu.com/f?kw=領域少女
也就是說kw=前面不變,變的是后面的名稱
2.接下來點進一個帖子
從中可以看到點擊完的地址--->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=*
4.用正則找出這些帖子的鏈接
因為/p/中/是匹配字符,所以要用\屏蔽效果
grep '<a rel="noreferrer" href="\/p\/*' a.txt |awk '{print $3}' |awk -F'"' '{print $2}' | awk -F'/' '{print $3}'
5.分析單個帖子
在網頁找到圖片右鍵,復制圖片地址
到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}'
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