用python批量爬取圖片

<code>工具:pycharm
python版本:3.6.*
使用到的庫:requests、BeautifulSoup/<code>


用python批量爬取圖片

1.主界面


用python批量爬取圖片

2.圖片展示界面

主界面中展示的是各個圖片主題信息,點入之後,展示此主題的全部圖片。

通過拼接主界面的網站,爬取主題圖片的網址,然後爬取該網址內的全部圖片,主要邏輯還是自己看代碼吧。本人也是第一次學習通過代碼批量下載圖片,在邏輯上可能不是很清晰,希望不要噴我,哈哈哈。。。


創建完項目之後,首先導入庫:

<code>import requests
from bs4 import BeautifulSoup
import os
import urllib.request/<code>

主要代碼部分:

<code># 爬取頁面資源
def getPage(url):
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
}
r = requests.get(url, headers=headers)
try:
r.raise_for_status()
except:
print("訪問異常:" + r.status_code)
data = r.text
# print(data)
soup = BeautifulSoup(data, 'html.parser')
# print(soup)
items = soup.find_all(class_='pic')

for item in items[:-3]:
name = item.em.text
print("圖片主題:" + name)
the_url = 'http://sj.zol.com.cn' + item.get('href')
print('http://sj.zol.com.cn' + item.get('href'))
downImg(the_url, "IMG_data/" + name)


# 下載圖片:
def downImg(url, path):
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
}
r = requests.get(url, headers=headers)
try:
r.raise_for_status()
except:
print("訪問異常:" + r.status_code)
data = r.text
soup = BeautifulSoup(data, 'html.parser')
# 需要爬取的數量
num = int(str(soup.span.text).split('/')[1].split(')')[0]);
# 默認選擇第一個清晰度的圖片
type = str(soup.dd.a.get('href'))
# 拼接高清圖片的位置:
type_0 = type.split('_')[0] + '_'
type_1 = '_' + type.split('_')[-1]

for id in range(num):
the_imgid = 'img' + str((id + 1))
# 縮略圖位置
the_url = soup.find(id=the_imgid).a.get('href')
imgId = str(the_url).split('_')[-1].split(".")[0]
img_url = 'http://sj.zol.com.cn' + type_0 + imgId + type_1
print(img_url)
# 判斷文件是否存在,如果不存在則進行刪除(猶豫碰到了線程阻塞問題,為了避免重複下載,只要該主題的文件夾存在就直接掠過,不爬取)
if not os.path.exists(path):
os.mkdir(path)
else:

return
rrr = requests.get(img_url, headers=headers)
try:
rrr.raise_for_status()
ss = BeautifulSoup(rrr.text, 'html.parser')
aa = ss.img.get('src')
urllib.request.build_opener().addheaders = headers
if not os.path.exists(path + '/' + str(id) + '.jpg'):
urllib.request.urlretrieve(aa, path + '/' + str(id) + '.jpg')
except:
print('獲取失敗!')

print(path + ",下載完成!")


if __name__ == '__main__':
# 找一個主界面尋找規律
# getPage(url)http://sj.zol.com.cn/bizhi/new_1.html
for num in range(100):
url = "http://sj.zol.com.cn/bizhi/new_" + str(num + 1) + ".html"
getPage(url)
/<code>

運行成功之後,下載的文件默認存放在當前項目路徑下:


用python批量爬取圖片

圖片


分享到:


相關文章: