摘自:https://www.cnblogs.com/saneri/p/9870901.html
原來文章中的代碼,已經失效,本人只是簡單的修改了一下。
#coding:utf-8
import requests
import os
from bs4 import BeautifulSoup
import time
#訪問的域名地址
all_url = 'http://www.mzitu.com'
#配置header 請求頭
headers_w = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
'Referer': 'http://www.mzitu.com'
}
headers_i = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
'Referer': 'http://i3.mmzztt.com'
}
#發送get請求,獲取某個網頁,並使用.text屬性打印出源碼信息
start_html = requests.get(all_url,headers=headers_w)
#print(start_html.text)
#定義保存地址.
path = 'D:\\images\\'
#尋求最大頁數
#我們使用bs4模塊開從html文件中提取數據,使用BeautifulSoup模塊解析代碼
soup = BeautifulSoup(start_html.text,'html.parser')
#print(soup)
#找出源碼中所有包含class_='page-numbers'的a標籤,會以一個列表的形式保存
page = soup.find_all('a',class_='page-numbers')
#print(page)
#取出next的上一個頁面數199
max_page = page[-2].text
#print(max_page)
#
same_url = "http://www.mzitu.com/page/"
for i in range(1,int(max_page)+1):
#構造每頁的url
page_url = same_url + str(i)
#print(page_url)
#請求每頁的url
get_page_url = requests.get(page_url,headers=headers_w)
#加載每頁源碼內容
page_soup = BeautifulSoup(get_page_url.text,'html.parser')
#print(page_soup)
# 將div標籤中包含class_=''postlist取出,在取出a標籤中target=_blank的標籤內容.
get_all_a = soup.find('div',class_='postlist').find_all('a',target='_blank')
#print(get_all_a)
for a in get_all_a:
#print(a)
#從標籤中獲取所有文字內容
title = a.get_text()
#print(title)
if title != '':
print("準備爬取:%s" %(title))
#處理字符串,先去除空行,然後將?號替換爲空,再將':'替換成空行
#判斷目錄是否存在
#print(path + title.strip().replace('?','').replace(':',''))
if not os.path.exists(path + title.strip().replace('?','').replace(':','')):
os.makedirs(path + title.strip().replace('?','').replace(':',''))
# 改變當前工作目錄;相當於shell下cd
os.chdir(path + title.strip().replace('?', '').replace(':', ''))
# 獲取每一張圖片頁面的url,如http://www.mzitu.com/155568
href = a.get('href')
#print(href)
# 圖片url中取出圖片的頁數和jpg結尾的圖片地址
html = requests.get(href,headers=headers_w)
#print("html: %s" % html)
mess = BeautifulSoup(html.text,'html.parser')
#print(mess)
pic_max = mess.find_all('span')
# pic_max[10] 取出來的是圖片頁數,如<span>41</span>、<span>42</span>
#print(pic_max[9])
pic_max = pic_max[9].text
print(pic_max)
if len(os.listdir(path+title.strip().replace('?','').replace(':',''))) >= int(pic_max):
print('已經保存完畢,跳過')
continue
for num in range(1,int(pic_max)+1):
#print(num)
pic = href + '/' + str(num)
# 打印出url如下:http://www.mzitu.com/155192/44
#print(pic)
#從pic的url中取出圖片地址
html = requests.get(pic,headers=headers_w)
#print(html.url)
mess = BeautifulSoup(html.text,'html.parser')
#print(mess)
pic_url = mess.find('img', alt=title)
#打印出圖片地址: <img alt="外拍精彩呈現" src="http://i3.mmzztt.com/2018/11/01a02.jpg"/>
#print(pic_url)
html_img = requests.get(pic_url.get('src'),headers=headers_i)
#請求每張圖片的下載url:http://i.meizitu.net/2018/11/02f33.jpg
#print(html_img.url)
file_name = pic_url.get('src').split('/')[-1]
#print(file_name)
with open(file_name,'wb') as f :
f.write(html_img.content)
print('圖片 %s 保存完成' %(file_name))
time.sleep(1)
print('第',i,'頁爬取完成.')