1. 程式人生 > >Python爬蟲之爬取煎蛋網妹子圖

Python爬蟲之爬取煎蛋網妹子圖

創建目錄 req add 註意 not 相同 esp mpi python3

這篇文章通過簡單的Python爬蟲(未使用框架,僅供娛樂)獲取並下載煎蛋網妹子圖指定頁面或全部圖片,並將圖片下載到磁盤。

首先導入模塊:urllib.request、re、os

import urllib.request
import re
import os

urllib.request模塊用於獲取HTML頁面數據

re模塊用於通過正則表達式解析並截取HTML頁面圖片url

os模塊用於文件夾相關操作

代碼不多,直接貼出來,代碼解釋在註釋中:

def crawl_jiandan(page, path):
    """
    :param page:獲取指定頁面數據,值為0或超過最大值則爬取全部數據
    :param path:文件存儲路徑,沒有目錄則創建目錄
    
""" if page < 0: return # 路徑是否存在,不存在則創建目錄 if not os.path.exists(path): os.mkdir(path) # 切換到目錄 os.chdir(path) # 煎蛋網妹子圖首頁 url = http://jandan.net/ooxx/page-%d#comments % page while True: request = urllib.request.Request(url) request.add_header(
User-Agent, Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:54.0) Gecko/20100101 Firefox/54.0) with urllib.request.urlopen(request) as response: html = response.read().decode(utf-8) # print(html) items = re.findall(re.compile(r<div class="text"><span class="righttext"><a
rhref="http://.+">[0-9]+</a></span><p><a rhref="//(.+\.jpg)" target="_blank" class="view_img_link">), html) next_url = re.findall(re.compile(r<a title="Older Comments" href="( rhttp://jandan.net/ooxx/page-[0-9]+#comments)" rclass="previous-comment-page">), html) for item in items: filename = item.split(/)[-1] # 目錄下是否已存在相同文件名,不存在則下載 if not os.path.exists(filename): print(item) urllib.request.urlretrieve(http:// + item, filename) if not len(next_url): return else: url = next_url[0] crawl_jiandan(1, /Volumes/KE/IT源碼/Python3/Python爬蟲/煎蛋網妹子圖)

打開本次磁盤,效果如下:

技術分享

這裏只顯示了部分圖像,有興趣的可以下載煎蛋網所有妹子圖,只需在上述函數中第一個參數傳0即可

註意:此文僅供參考和娛樂,代碼還不夠嚴謹。

Python爬蟲之爬取煎蛋網妹子圖