Python 爬蟲入門(二)——爬取妹子圖

來源:互聯網
上載者:User

標籤:fir   odi   地址   mon   構造   content   檔案   mozilla   下載   

Python 爬蟲入門

聽說你寫代碼沒動力?本文就給你動力,爬取妹子圖。如果這也沒動力那就沒救了。

GitHub 地址: https://github.com/injetlee/Python/blob/master/%E7%88%AC%E8%99%AB%E9%9B%86%E5%90%88/meizitu.py

公眾號:【智能製造專欄】。歡迎關注,分享智能製造與編程那些事。

爬蟲成果

當你運行代碼後,檔案夾就會越來越多,如果爬完的話會有2000多個檔案夾,20000多張圖片。不過會很耗時間,可以在最後的代碼設定爬取頁碼範圍。

本文目標
  1. 熟悉 Requests 庫,Beautiful Soup 庫
  2. 熟悉多線程爬取
  3. 送福利,妹子圖
網站結構

我們從 http://meizitu.com/a/more_1.html 這個連結進去,介面一所示

圖一:

可以看到是一組一組的套圖,點擊任何一組圖片會進入到詳情介面,二所示

圖二:

可以看到圖片是依次排開的,一般會有十張左右的圖片。

實現思路

看了介面的結構,那麼我們的思路就有了。

  1. 構造 url 連結,去請求圖一所示的套圖列表介面,拿到每一個頁面中的套圖列表。
  2. 分別進入每個套圖中去,下載相應的圖片。
代碼說明
  1. 下載介面的函數,利用 Requests 很方便實現。

    def download_page(url):    '''    用於下載頁面    '''    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"}    r = requests.get(url, headers=headers)    r.encoding = 'gb2312'    return r.text
  2. 擷取圖一所示的所有套圖列表,函數中 link 表示套圖的連結,text表示套圖的名字

    def get_pic_list(html):    '''    擷取每個頁面的套圖列表,之後迴圈調用get_pic函數擷取圖片    '''    soup = BeautifulSoup(html, 'html.parser')    pic_list = soup.find_all('li', class_='wp-item')    for i in pic_list:        a_tag = i.find('h3', class_='tit').find('a')        link = a_tag.get('href')  # 套圖連結        text = a_tag.get_text()   # 套圖名字        get_pic(link, text)
  3. 傳入上一步中擷取到的套圖連結及套圖名字,擷取每組套圖裡面的圖片,並儲存,我在代碼中注釋了。

    def get_pic(link, text):    '''    擷取當前頁面的圖片,並儲存    '''    html = download_page(link)  # 下載介面    soup = BeautifulSoup(html, 'html.parser')    pic_list = soup.find('div', id="picture").find_all('img')  # 找到介面所有圖片    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"}    create_dir('pic/{}'.format(text))    for i in pic_list:        pic_link = i.get('src')  # 拿到圖片的具體 url        r = requests.get(pic_link, headers=headers)  # 下載圖片,之後儲存到檔案        with open('pic/{}/{}'.format(text, pic_link.split('/')[-1]), 'wb') as f:            f.write(r.content)            time.sleep(1)
完整代碼

完整代碼如下,包括了建立檔案夾,利用多線程爬取,我設定的是5個線程,可以根據自己機器自己來設定一下。

import requestsimport osimport timeimport threadingfrom bs4 import BeautifulSoupdef download_page(url):    '''    用於下載頁面    '''    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"}    r = requests.get(url, headers=headers)    r.encoding = 'gb2312'    return r.textdef get_pic_list(html):    '''    擷取每個頁面的套圖列表,之後迴圈調用get_pic函數擷取圖片    '''    soup = BeautifulSoup(html, 'html.parser')    pic_list = soup.find_all('li', class_='wp-item')    for i in pic_list:        a_tag = i.find('h3', class_='tit').find('a')        link = a_tag.get('href')        text = a_tag.get_text()        get_pic(link, text)def get_pic(link, text):    '''    擷取當前頁面的圖片,並儲存    '''    html = download_page(link)  # 下載介面    soup = BeautifulSoup(html, 'html.parser')    pic_list = soup.find('div', id="picture").find_all('img')  # 找到介面所有圖片    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"}    create_dir('pic/{}'.format(text))    for i in pic_list:        pic_link = i.get('src')  # 拿到圖片的具體 url        r = requests.get(pic_link, headers=headers)  # 下載圖片,之後儲存到檔案        with open('pic/{}/{}'.format(text, pic_link.split('/')[-1]), 'wb') as f:            f.write(r.content)            time.sleep(1)   # 休息一下,不要給網站太大壓力,避免被封def create_dir(name):    if not os.path.exists(name):        os.makedirs(name)def execute(url):    page_html = download_page(url)    get_pic_list(page_html)def main():    create_dir('pic')    queue = [i for i in range(1, 72)]   # 構造 url 連結 頁碼。    threads = []    while len(queue) > 0:        for thread in threads:            if not thread.is_alive():                threads.remove(thread)        while len(threads) < 5 and len(queue) > 0:   # 最大線程數設定為 5            cur_page = queue.pop(0)            url = 'http://meizitu.com/a/more_{}.html'.format(cur_page)            thread = threading.Thread(target=execute, args=(url,))            thread.setDaemon(True)            thread.start()            print('{}正在下載{}頁'.format(threading.current_thread().name, cur_page))            threads.append(thread)if __name__ == '__main__':    main()

好了,之後運行,我們的爬蟲就會孜孜不倦的為我們下載漂亮妹子啦。

Python 爬蟲入門(二)——爬取妹子圖

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.