Python爬蟲入門教程:蜂鳥網圖片爬取

1. 蜂鳥網圖片--簡介

國慶假日結束了,新的工做又開始了,今天咱們繼續爬取一個網站,這個網站爲 http://image.fengniao.com/ ,蜂鳥一個攝影大牛彙集的地方,本教程請用來學習,不要用於商業目的,不出意外,蜂鳥是有版權保護的網站。php


 

2. 蜂鳥網圖片--網站分析

第一步,分析要爬取的網站有沒有方法爬取,打開頁面,找分頁html

http://image.fengniao.com/index.php?action=getList&class_id=192&sub_classid=0&page=1&not_in_id=5352384,5352410 http://image.fengniao.com/index.php?action=getList&class_id=192&sub_classid=0&page=2&not_in_id=5352384,5352410 http://image.fengniao.com/index.php?action=getList&class_id=192&sub_classid=0&page=3&not_in_id=5352384,5352410 http://image.fengniao.com/index.php?action=getList&class_id=192&sub_classid=0&page=4&not_in_id=5352384,5352410

上面的頁面發現一個關鍵的參數page=1這個就是頁碼了,可是另外一個比較頭疼的問題是,他沒有最後的頁碼,這樣咱們沒有辦法肯定循環次數,因此後面的代碼編寫中,只能使用whilepython

這個地址返回的是JSON格式的數據,這個對爬蟲來講,很是友好!省的咱們用正則表達式分析了。
在這裏插入圖片描述git

分析這個頁面的頭文件,查閱是否有反爬措施github

在這裏插入圖片描述

發現除了HOST和User-Agent之外,沒有特殊的點,大網站就是任性,沒啥反爬,可能壓根不在意這個事情。正則表達式

第二步,分析圖片詳情頁面,在咱們上面獲取到的JSON中,找到關鍵地址
在這裏插入圖片描述json

關鍵地址打開以後,這個地方有一個比較騷的操做了,上面圖片中標註的URL選的很差,剛好是一個文章了,咱們要的是組圖,從新提供一個新連接 http://image.fengniao.com/slide/535/5352130_1.html#p=1app

打開頁面,你可能直接去找規律了,找到下面的一堆連接,可是這個操做就有點複雜了,咱們查閱上述頁面的源碼ide

http://image.fengniao.com/slide/535/5352130_1.html#p=1 http://image.fengniao.com/slide/535/5352130_1.html#p=2 http://image.fengniao.com/slide/535/5352130_1.html#p=3 ....

網頁源碼中發現了,這麼一塊區域
在這裏插入圖片描述學習

大膽的猜想一下,這個應該是圖片的JSON,只是他打印在了HTML中,咱們只須要用正則表達式進行一下匹配就行了,匹配到以後,而後進行下載。

第三步,開始擼代碼。


 

3. 蜂鳥網圖片--寫代碼

 1 from http_help import R  # 這個文件本身去上篇博客找,或者去github找
 2 import threading
 3 import time
 4 import json
 5 import re
 6 
 7 img_list = []
 8 imgs_lock = threading.Lock()  #圖片操做鎖
 9 
10 
11 # 生產者類
12 class Product(threading.Thread):
13 
14     def __init__(self):
15         threading.Thread.__init__(self)
16 
17         self.__headers = {"Referer":"http://image.fengniao.com/",
18                           "Host": "image.fengniao.com",
19                           "X-Requested-With":"XMLHttpRequest"
20                           }
21         #連接模板
22         self.__start = "http://image.fengniao.com/index.php?action=getList&class_id=192&sub_classid=0&page={}&not_in_id={}"
23         self.__res = R(headers=self.__headers)
24 
25 
26     def run(self):
27 
28         # 由於不知道循環次數,全部採用while循環
29         index = 2 #起始頁碼設置爲1
30         not_in = "5352384,5352410"
31         while True:
32             url  = self.__start.format(index,not_in)
33             print("開始操做:{}".format(url))
34             index += 1
35 
36             content = self.__res.get_content(url,charset="gbk")
37 
38             if content is None:
39                 print("數據可能已經沒有了====")
40                 continue
41 
42             time.sleep(3)  # 睡眠3秒
43             json_content = json.loads(content)
44 
45             if json_content["status"] == 1:
46                 for item in json_content["data"]:
47                     title = item["title"]
48                     child_url =  item["url"]   # 獲取到連接以後
49 
50                     img_content = self.__res.get_content(child_url,charset="gbk")
51 
52                     pattern = re.compile('"pic_url_1920_b":"(.*?)"')
53                     imgs_json = pattern.findall(img_content)
54                     if len(imgs_json) > 0:
55 
56                         if imgs_lock.acquire():
57                             img_list.append({"title":title,"urls":imgs_json})   # 這個地方,我用的是字典+列表的方式,主要是想後面生成文件夾用,你能夠進行改造
58                             imgs_lock.release()
59 
60 #小編整理一套Python資料和PDF,有須要Python學習資料能夠加學習羣:1004391443,反正閒着也是閒着呢,不如學點東西啦~~

 

上面的連接已經生成,下面就是下載圖片了,也很是簡單

# 消費者
class Consumer(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.__res = R()

    def run(self):

        while True:
            if len(img_list) <= 0:
                continue  # 進入下一次循環

            if imgs_lock.acquire():

                data = img_list[0]
                del img_list[0]  # 刪除第一項

                imgs_lock.release()

            urls =[url.replace("\\","") for url in data["urls"]]

            # 建立文件目錄
            for item_url in urls:
               try:
                   file =  self.__res.get_file(item_url)
                   # 記得在項目根目錄先把fengniaos文件夾建立完畢
                   with open("./fengniaos/{}".format(str(time.time())+".jpg"), "wb+") as f:
                       f.write(file)
               except Exception as e:
                   print(e)

 

代碼走起,結果
在這裏插入圖片描述

相關文章
相關標籤/搜索