Python3爬取妹子圖中的一組套圖

利用python的正則表達式抓取一位妹子的套取,網址爲:

http://www.mzitu.com/157693

1,打開網站,依次點擊第1頁,第2頁,第3頁,第4頁,...

發現網址有規律:

http://www.mzitu.com/157693/1
http://www.mzitu.com/157693/2
http://www.mzitu.com/157693/3
http://www.mzitu.com/157693/4

其中第1頁網址後面的“/1”可有可無,但是爲了有規律,還是加上。

2,在最大的頁數上單擊右鍵,也就是在53頁處單擊右鍵,

 

選擇【檢查】,如圖所示:

可以看到,標題在<h2>...</h2>中,頁數在<span>...</span>中,而且只有幾個<span>。

利用如下正則匹配提取頁數信息,最大頁數是提取出列表中的最後一位,注意提取出的頁數類型是字符串類型,不是整型。

re.compile('<span>(\d+)</span>', re.S)

利用如下正則匹配標題,提取出的列表中只有單獨一個標題。

re.compile('<h2.*?>(.*?)</h2>', re.S) 

3,打開任意一個圖片的頁數所在的網址:如

http://www.mzitu.com/157693/3

單擊鼠標右鍵,選擇【檢查】,找到圖片的超鏈接:

可以看到,圖片的超鏈接在<p><a><img...></a></p>中的src屬性。

利用如下正則提取圖片的超鏈接:

re.compile('<p>.*?<img.*?src="(.*?)".*?>.*?</p>', re.S)

4,因此,根據頁數規律找出網址,在每個網址中提取出圖片的超鏈接,根據圖片的超鏈接下載這張圖即可。

import requests
# from requests.exceptions import RequestException
import re
import random
import time
import os


def find_maxpage():
    url = 'http://www.mzitu.com/157693'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        'Referer': 'http://www.mzitu.com'    # 必須有這個Referer才行
    }
    response = requests.get(url, headers=headers)
    html = response.text
    pattern = re.compile('<span>(\d+)</span>', re.S)  # 提取出所有顯示的頁數
    pages = re.findall(pattern, html)
    # print(pages)
    # print(type(pages))
    max_page = pages[-1]  # 最大頁數在最後一位
    # print(max_page)
    # print(type(max_page))
    return max_page


def find_title():
    url = 'http://www.mzitu.com/157693'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        'Referer': 'http://www.mzitu.com'
    }
    response = requests.get(url, headers=headers)
    html = response.text
    pattern_name = re.compile('<h2.*?>(.*?)</h2>', re.S)  # 提取標題
    names = re.findall(pattern_name, html)
    # print(names)
    # print(type(names))
    title = names[0]  # 列表中只有一個字符串,作爲標題
    print(title)
    return title


def download_picture(page):
    base_url = 'http://www.mzitu.com/157693/'
    url = base_url + str(page)
    headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
                'Referer': 'http://www.mzitu.com'
            }
    response = requests.get(url, headers=headers)
    html = response.text

    pattern = re.compile('<p>.*?<img.*?src="(.*?)".*?>.*?</p>', re.S)  # 提取出圖片的超鏈接
    href = re.findall(pattern, html)  # 注意這是一個列表,只包含一個超鏈接
    href_picture = href[0]
    print(href_picture)
    title_end = href_picture.split(r'/')[-1]    # 圖片名稱的後部分
    base_title = find_title()
    title = base_title + title_end

    file_path = r'F:\MeiZi_Pictures' + os.path.sep + base_title
    if not os.path.exists(file_path):
        os.makedirs(file_path)    # 如果存儲路徑不存在,則進行創建
    os.chdir(file_path)           # 改變存儲路徑到file_path

    response = requests.get(url=href_picture, headers=headers)
    content = response.content
    picture_name = title[:]
    print(picture_name)
    with open(picture_name, 'wb') as f:
        f.write(content)
    time.sleep(random.random() * 3)


if __name__ == '__main__':
    page_all = int(find_maxpage())
    for item in range(1, page_all + 1):
        download_picture(item)
        print('第{}張圖片下載完畢'.format(item))

運行過程:

# 開始
https://i.meizitu.net/2018/11/06c01.jpg
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色06c01.jpg
第1張圖片下載完畢
https://i.meizitu.net/2018/11/06c02.jpg
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色06c02.jpg
第2張圖片下載完畢
https://i.meizitu.net/2018/11/06c03.jpg
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色06c03.jpg
第3張圖片下載完畢
# 中間省略...
# 結尾
https://i.meizitu.net/2018/11/06c51.jpg
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色06c51.jpg
第51張圖片下載完畢
https://i.meizitu.net/2018/11/06c52.jpg
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色06c52.jpg
第52張圖片下載完畢
https://i.meizitu.net/2018/11/06c53.jpg
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色
火辣身材力壓潘曉婷 檯球寶貝楊晨晨魅惑私房盡顯豪放本色06c53.jpg
第53張圖片下載完畢

Process finished with exit code 0

存儲結果:

下載完成。

6,BeautifulSoup的簡單版本:用BeautifulSoup解析更加簡單。

import requests
from bs4 import BeautifulSoup
import random
import time


url = 'http://www.mzitu.com/157693'
header = {
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
            'Referer': 'http://www.mzitu.com'
        }
html = requests.get(url=url, headers=header)
soup = BeautifulSoup(html.text, 'lxml')

#最大頁數在span標籤中的第10個
pic_max = soup.find_all('span')[10].get_text()    #用get_text()獲取其中的文本
print(pic_max)
#找標題
title = soup.find('h2', class_='main-title').get_text()
print(title)

#輸出每個圖片頁面的地址
"""
每個圖片的網址有規律1,2,3,4...
http://www.mzitu.com/157693/1
http://www.mzitu.com/157693/2
http://www.mzitu.com/157693/3
http://www.mzitu.com/157693/4
"""
for i in range(1, int(pic_max) + 1):
    href = url + '/' + str(i)
    print(href)
    html = requests.get(href, headers=header)
    print('狀態碼爲:{}'.format(html.status_code))
    mess = BeautifulSoup(html.text, 'lxml')
    # 圖片地址在img標籤alt屬性和標題一樣的地方
    pic_url = mess.find('img', alt=title)
    print(pic_url)
    html = requests.get(pic_url['src'], headers=header)    #pic_url的屬性src中才是圖片真正的網址
    print('狀態碼爲:{}'.format(html.status_code))
    #獲取圖片的名字方便命名
    file_name = title + pic_url['src'].split(r'/')[-1]
    #圖片不是文本文件,需要以二進制格式寫入,所以是html.content
    with open(file_name, 'wb') as f:
        f.write(html.content)    # 圖片直接存儲在當前目錄下
    sleep_time = random.randint(0, 5) + random.random()
    time.sleep(sleep_time)  # 自定義延時

==============================================

上面都是直接存圖片,還有另一種方法:先讀入再存儲

需要先在開頭導入:

from io import BytesIO
from PIL import Image

再將

with open(file_name, 'wb') as f:
    f.write(html.content)

修改爲:

picture = Image.open(BytesIO(html.content))
picture.save(file_name)

即可。發現這樣存儲文件稍微小一些。

參考:

https://blog.csdn.net/baidu_35085676/article/details/68958267

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章