python爬取性感美女圖片

需求:最近對python爬蟲感興趣,於是也依葫蘆畫瓢試着用爬蟲爬取之前喜歡的網站上的美女圖片,網站:http://www.mm131.com/xinggan,其中每一套圖都是一張一個頁面,存一套圖如果是手動得點翻幾十個頁面,但現在用爬蟲的話,就很方便了,只需輸入套圖的id,輕輕鬆鬆就可以把美女存到硬盤了。

大神說:talk is cheap show me the code!

接下來說下一般網頁爬蟲的的過程

1.查看目標網站頁面的源代碼,找到需要爬取的內容
2.用正則或其他如xpath/bs4的工具獲取爬取內容
3.寫出完整的python代碼,實現爬取過程

1.目標網址

url:http://www.mm131.com/xinggan/2373.html
 美女圖片
漂亮吧!!

2.分析源代碼

F12可以找到如下2行內容

src="http://img1.mm131.com/pic/2373/1.jpg"
span class="page-ch">共56頁

我們得到如下信息

我們點擊第二頁和第三頁繼續看源碼

3.爬取圖片

我們試着爬取第一個頁面的圖,直接上代碼:

import requests
import re
url = 'http://www.mm131.com/xinggan/2373.html'
html = requests.get(url).text           #讀取整個頁面爲文本
a = re.search(r'img alt=.* src="(.*?)" /',html,re.S)  #匹配圖片url
print(a.group(1))</code>
得到:
http://img1.mm131.com/pic/2373/1.jpg

接下來我們需要把圖片保存在本地:

pic= requests.get(a, timeout=2)  #time設置超時,防止程序苦等
fp = open(pic,'wb')    #以二進制寫入模式新建一個文件
fp.write(pic.content)  #把圖片寫入文件
fp.close()

這樣,你的本地就會有第一張美女圖了,

第一張既然已經保存了,那剩下的也都不要放過,繼續放代碼:

4.繼續把代碼補全

載入所需模塊,並設置圖片存放目錄

#coding:utf-8
import requests
import re
import os
from bs4 import BeautifulSoup
pic_id = raw_input('Input pic id: ')
os.chdir("G:\pic")
homedir = os.getcwd()
print("當前目錄 %s" % homedir )
fulldir = unicode(os.path.join(homedir,pic_id),encoding='utf-8')  #圖片保存在指定目錄,並根據套圖id設置目錄
if not os.path.isdir(fulldir):
    os.makedirs(fulldir)

因爲需要不停翻頁才能獲取圖片,所以我們先獲取總頁數

url='http://www.mm131.com/xinggan/%s.html' % pic_id
html = requests.get(url).text
#soup = BeautifulSoup(html)
soup = BeautifulSoup(html, 'html.parser')  #使用soup取關鍵字,上一行會報錯UserWarning: No parser was explicitly specified
ye = soup.span.string
ye_count = re.search('\d+',ye)
print('pages:共%d頁' % int(ye_count.group()))

主函數

def downpic(pic_id):
    n = 1
    url='http://www.mm131.com/xinggan/%s.html' % pic_id
    while n <= int(ye_count.group()):  #翻完停止
        #下載圖片
        try:
            if not n == 1:
                url='http://www.mm131.com/xinggan/%s_%s.html' % (pic_id,n) #url隨着n的值變化的
            html = requests.get(url).text
            pic_url = re.search(r'img alt=.* src="(.*?)" /',html,re.S)   #使用正則去關鍵字
            pic_s = pic_url.group(1)
            print(pic_s)
            pic= requests.get(pic_s, timeout=2)
            pic_cun = fulldir + '\\' + str(n) + '.jpg'
            fp = open(pic_cun,'wb')
            fp.write(pic.content)
            fp.close()
            n += 1
        except requests.exceptions.ConnectionError:
            print("【錯誤】當前圖片無法下載")
            continue
if __name__ == '__main__':
    downpic(pic_id)
  • 程序跑起來

python

python

5.好了,收工

看着硬盤裏的圖片是不是爽歪歪,當然爬蟲能幹的 不光只是下圖片,它還可以做其他一些事,比如爬取12306火車信息,或求職網的職位信息,或者其他,總之趕緊把此技能get起來,豐富起來吧!

參考http://www.jianshu.com/p/19c846daccb3

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