日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
基于Python的Scrapy爬蟲入門:代碼詳解

一、內(nèi)容分析

創(chuàng)新互聯(lián)專注于臨西網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗。 熱誠為您提供臨西營銷型網(wǎng)站建設(shè),臨西網(wǎng)站制作、臨西網(wǎng)頁設(shè)計、臨西網(wǎng)站官網(wǎng)定制、微信平臺小程序開發(fā)服務(wù),打造臨西網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供臨西網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。

接下來創(chuàng)建一個爬蟲項目,以 圖蟲網(wǎng) 為例抓取里面的圖片。在頂部菜單“發(fā)現(xiàn)” “標(biāo)簽”里面是對各種圖片的分類,點擊一個標(biāo)簽,比如“美女”,網(wǎng)頁的鏈接為:https://tuchong.com/tags/美女/,我們以此作為爬蟲入口,分析一下該頁面:

打開頁面后出現(xiàn)一個個的圖集,點擊圖集可全屏瀏覽圖片,向下滾動頁面會出現(xiàn)更多的圖集,沒有頁碼翻頁的設(shè)置。Chrome右鍵“檢查元素”打開開發(fā)者工具,檢查頁面源碼,內(nèi)容部分如下:

 
 
 
  1.  
  2.  
  3.      
  4.  
  5.          
  6.  
  7.             

可以判斷每一個li.gallery-item是一個圖集的入口,存放在ul.pagelist-wrapper下,div.widget-gallery是一個容器,如果使用 xpath 選取應(yīng)該是://div[@class=”widget-gallery”]/ul/li,按照一般頁面的邏輯,在li.gallery-item下面找到對應(yīng)的鏈接地址,再往下深入一層頁面抓取圖片。

但是如果用類似 Postman 的HTTP調(diào)試工具請求該頁面,得到的內(nèi)容是:

 
 
 
  1.  
  2.  
  3.     
 
  •  
  •  

    也就是并沒有實際的圖集內(nèi)容,因此可以斷定頁面使用了Ajax請求,只有在瀏覽器載入頁面時才會請求圖集內(nèi)容并加入div.widget-gallery中,通過開發(fā)者工具查看XHR請求地址為:

     
     
     
    1. https://tuchong.com/rest/tags/美女/posts?page=1&count=20&order=weekly&before_timestamp= 

    參數(shù)很簡單,page是頁碼,count是每頁圖集數(shù)量,order是排序,before_timestamp為空,圖蟲因為是推送內(nèi)容式的網(wǎng)站,因此before_timestamp應(yīng)該是一個時間值,不同的時間會顯示不同的內(nèi)容,這里我們把它丟棄,不考慮時間直接從***的頁面向前抓取。

    請求結(jié)果為JSON格式內(nèi)容,降低了抓取難度,結(jié)果如下:

     
     
     
    1.  
    2.   "postList": [ 
    3.  
    4.     { 
    5.  
    6.       "post_id": "15624611", 
    7.  
    8.       "type": "multi-photo", 
    9.  
    10.       "url": "https://weishexi.tuchong.com/15624611/", 
    11.  
    12.       "site_id": "443122", 
    13.  
    14.       "author_id": "443122", 
    15.  
    16.       "published_at": "2017-10-28 18:01:03", 
    17.  
    18.       "excerpt": "10月18日", 
    19.  
    20.       "favorites": 4052, 
    21.  
    22.       "comments": 353, 
    23.  
    24.       "rewardable": true, 
    25.  
    26.       "parent_comments": "165", 
    27.  
    28.       "rewards": "2", 
    29.  
    30.       "views": 52709, 
    31.  
    32.       "title": "微風(fēng)不燥  秋意正好", 
    33.  
    34.       "image_count": 15, 
    35.  
    36.       "images": [ 
    37.  
    38.         { 
    39.  
    40.           "img_id": 11585752, 
    41.  
    42.           "user_id": 443122, 
    43.  
    44.           "title": "", 
    45.  
    46.           "excerpt": "", 
    47.  
    48.           "width": 5016, 
    49.  
    50.           "height": 3840 
    51.  
    52.         }, 
    53.  
    54.         { 
    55.  
    56.           "img_id": 11585737, 
    57.  
    58.           "user_id": 443122, 
    59.  
    60.           "title": "", 
    61.  
    62.           "excerpt": "", 
    63.  
    64.           "width": 3840, 
    65.  
    66.           "height": 5760 
    67.  
    68.         }, 
    69.  
    70.         ... 
    71.  
    72.       ], 
    73.  
    74.       "title_image": null, 
    75.  
    76.       "tags": [ 
    77.  
    78.         { 
    79.  
    80.           "tag_id": 131, 
    81.  
    82.           "type": "subject", 
    83.  
    84.           "tag_name": "人像", 
    85.  
    86.           "event_type": "", 
    87.  
    88.           "vote": "" 
    89.  
    90.         }, 
    91.  
    92.         { 
    93.  
    94.           "tag_id": 564, 
    95.  
    96.           "type": "subject", 
    97.  
    98.           "tag_name": "美女", 
    99.  
    100.           "event_type": "", 
    101.  
    102.           "vote": "" 
    103.  
    104.         } 
    105.  
    106.       ], 
    107.  
    108.       "favorite_list_prefix": [], 
    109.  
    110.       "reward_list_prefix": [], 
    111.  
    112.       "comment_list_prefix": [], 
    113.  
    114.       "cover_image_src": "https://photo.tuchong.com/443122/g/11585752.webp", 
    115.  
    116.       "is_favorite": false 
    117.  
    118.     } 
    119.  
    120.   ], 
    121.  
    122.   "siteList": {...}, 
    123.  
    124.   "following": false, 
    125.  
    126.   "coverUrl": "https://photo.tuchong.com/443122/ft640/11585752.webp", 
    127.  
    128.   "tag_name": "美女", 
    129.  
    130.   "tag_id": "564", 
    131.  
    132.   "url": "https://tuchong.com/tags/%E7%BE%8E%E5%A5%B3/", 
    133.  
    134.   "more": true, 
    135.  
    136.   "result": "SUCCESS" 
    137.  

    根據(jù)屬性名稱很容易知道對應(yīng)的內(nèi)容含義,這里我們只需關(guān)心 postlist 這個屬性,它對應(yīng)的一個數(shù)組元素便是一個圖集,圖集元素中有幾項屬性我們需要用到:

    • url:單個圖集瀏覽的頁面地址
    • post_id:圖集編號,在網(wǎng)站中應(yīng)該是唯一的,可以用來判斷是否已經(jīng)抓取過該內(nèi)容
    • site_id:作者站點編號 ,構(gòu)建圖片來源鏈接要用到
    • title:標(biāo)題
    • excerpt:摘要文字
    • type:圖集類型,目前發(fā)現(xiàn)兩種,一種multi-photo是純照片,一種text是文字與圖片混合的文章式頁面,兩種內(nèi)容結(jié)構(gòu)不同,需要不同的抓取方式,本例中只抓取純照片類型,text類型直接丟棄
    • tags:圖集標(biāo)簽,有多個
    • image_count:圖片數(shù)量
    • images:圖片列表,它是一個對象數(shù)組,每個對象中包含一個img_id屬性需要用到

    根據(jù)圖片瀏覽頁面分析,基本上圖片的地址都是這種格式: https://photo.tuchong.com/{site_id}/f/{img_id}.jpg ,很容易通過上面的信息合成。

    二、創(chuàng)建項目

    1. 進(jìn)入cmder命令行工具,輸入workon scrapy 進(jìn)入之前建立的虛擬環(huán)境,此時命令行提示符前會出現(xiàn)(Scrapy) 標(biāo)識,標(biāo)識處于該虛擬環(huán)境中,相關(guān)的路徑都會添加到PATH環(huán)境變量中便于開發(fā)及使用。
    2. 輸入 scrapy startproject tuchong 創(chuàng)建項目 tuchong
    3. 進(jìn)入項目主目錄,輸入 scrapy genspider photo tuchong.com 創(chuàng)建一個爬蟲名稱叫 photo (不能與項目同名),爬取 tuchong.com 域名(這個需要修改,此處先輸個大概地址),的一個項目內(nèi)可以包含多個爬蟲

    經(jīng)過以上步驟,項目自動建立了一些文件及設(shè)置,目錄結(jié)構(gòu)如下:

     
     
     
    1. (PROJECT) 
    2.  
    3. │  scrapy.cfg 
    4.  
    5. │ 
    6.  
    7. └─tuchong 
    8.  
    9.     │  items.py 
    10.  
    11.     │  middlewares.py 
    12.  
    13.     │  pipelines.py 
    14.  
    15.     │  settings.py 
    16.  
    17.     │  __init__.py 
    18.  
    19.     │ 
    20.  
    21.     ├─spiders 
    22.  
    23.     │  │  photo.py 
    24.  
    25.     │  │  __init__.py 
    26.  
    27.     │  │ 
    28.  
    29.     │  └─__pycache__ 
    30.  
    31.     │          __init__.cpython-36.pyc 
    32.  
    33.     │ 
    34.  
    35.     └─__pycache__ 
    36.  
    37.             settings.cpython-36.pyc 
    38.  
    39.             __init__.cpython-36.pyc 
    • scrapy.cfg:基礎(chǔ)設(shè)置
    • items.py:抓取條目的結(jié)構(gòu)定義
    • middlewares.py:中間件定義,此例中無需改動
    • pipelines.py:管道定義,用于抓取數(shù)據(jù)后的處理
    • settings.py:全局設(shè)置
    • spiders\photo.py:爬蟲主體,定義如何抓取需要的數(shù)據(jù)

    三、主要代碼

    items.py 中創(chuàng)建一個TuchongItem類并定義需要的屬性,屬性繼承自 scrapy.Field 值可以是字符、數(shù)字或者列表或字典等等:

     
     
     
    1. import scrapy 
    2.  
    3. class TuchongItem(scrapy.Item): 
    4.  
    5.     post_id = scrapy.Field() 
    6.  
    7.     site_id = scrapy.Field() 
    8.  
    9.     title = scrapy.Field() 
    10.  
    11.     type = scrapy.Field() 
    12.  
    13.     url = scrapy.Field() 
    14.  
    15.     image_count = scrapy.Field() 
    16.  
    17.     images = scrapy.Field() 
    18.  
    19.     tags = scrapy.Field() 
    20.  
    21.     excerpt = scrapy.Field() 
    22.  
    23.     ... 

    這些屬性的值將在爬蟲主體中賦予。

    spiders\photo.py 這個文件是通過命令 scrapy genspider photo tuchong.com 自動創(chuàng)建的,里面的初始內(nèi)容如下:

     
     
     
    1. import scrapy 
    2.  
    3. class PhotoSpider(scrapy.Spider): 
    4.  
    5.     name = 'photo' 
    6.  
    7.     allowed_domains = ['tuchong.com'] 
    8.  
    9.     start_urls = ['http://tuchong.com/'] 
    10.  
    11.     def parse(self, response): 
    12.  
    13.         pass 

    爬蟲名 name,允許的域名 allowed_domains(如果鏈接不屬于此域名將丟棄,允許多個) ,起始地址 start_urls 將從這里定義的地址抓?。ㄔ试S多個)

    函數(shù) parse 是處理請求內(nèi)容的默認(rèn)回調(diào)函數(shù),參數(shù) response 為請求內(nèi)容,頁面內(nèi)容文本保存在 response.body 中,我們需要對默認(rèn)代碼稍加修改,讓其滿足多頁面循環(huán)發(fā)送請求,這需要重載 start_requests 函數(shù),通過循環(huán)語句構(gòu)建多頁的鏈接請求,修改后代碼如下:

     
     
     
    1. import scrapy, json 
    2.  
    3. from ..items import TuchongItem 
    4.  
    5. class PhotoSpider(scrapy.Spider): 
    6.  
    7.     name = 'photo' 
    8.  
    9.     # allowed_domains = ['tuchong.com'] 
    10.  
    11.     # start_urls = ['http://tuchong.com/'] 
    12.  
    13.  
    14.     def start_requests(self): 
    15.  
    16.         url = 'https://tuchong.com/rest/tags/%s/posts?page=%d&count=20&order=weekly'; 
    17.  
    18.         # 抓取10個頁面,每頁20個圖集 
    19.  
    20.         # 指定 parse 作為回調(diào)函數(shù)并返回 Requests 請求對象 
    21.  
    22.         for page in range(1, 11): 
    23.  
    24.             yield scrapy.Request(url=url % ('美女', page), callback=self.parse) 
    25.  
    26.  
    27.     # 回調(diào)函數(shù),處理抓取內(nèi)容填充 TuchongItem 屬性 
    28.  
    29.     def parse(self, response): 
    30.  
    31.         body = json.loads(response.body_as_unicode()) 
    32.  
    33.         items = [] 
    34.  
    35.         for post in body['postList']: 
    36.  
    37.             item = TuchongItem() 
    38.  
    39.             item['type'] = post['type'] 
    40.  
    41.             item['post_id'] = post['post_id'] 
    42.  
    43.             item['site_id'] = post['site_id'] 
    44.  
    45.             item['title'] = post['title'] 
    46.  
    47.             item['url'] = post['url'] 
    48.  
    49.             item['excerpt'] = post['excerpt'] 
    50.  
    51.             item['image_count'] = int(post['image_count']) 
    52.  
    53.             item['images'] = {} 
    54.  
    55.             # 將 images 處理成 {img_id: img_url} 對象數(shù)組 
    56.  
    57.             for img in post.get('images', ''): 
    58.  
    59.                 img_id = img['img_id'] 
    60.  
    61.                 url = 'https://photo.tuchong.com/%s/f/%s.jpg' % (item['site_id'], img_id) 
    62.  
    63.                 item['images'][img_id] = url 
    64.  
    65.             item['tags'] = [] 
    66.  
    67.             # 將 tags 處理成 tag_name 數(shù)組 
    68.  
    69.             for tag in post.get('tags', ''): 
    70.  
    71.                 item['tags'].append(tag['tag_name']) 
    72.  
    73.             items.append(item) 
    74.  
    75.         return items 

    經(jīng)過這些步驟,抓取的數(shù)據(jù)將被保存在 TuchongItem 類中,作為結(jié)構(gòu)化的數(shù)據(jù)便于處理及保存。

    前面說過,并不是所有抓取的條目都需要,例如本例中我們只需要 type=”multi_photo 類型的圖集,并且圖片太少的也不需要,這些抓取條目的篩選操作以及如何保存需要在pipelines.py中處理,該文件中默認(rèn)已創(chuàng)建類 TuchongPipeline 并重載了 process_item函數(shù),通過修改該函數(shù)只返回那些符合條件的 item,代碼如下:

     
     
     
    1. import scrapy, json 
    2.  
    3. from ..items import TuchongItem 
    4.  
    5. class PhotoSpider(scrapy.Spider): 
    6.  
    7.     name = 'photo' 
    8.  
    9.     # allowed_domains = ['tuchong.com'] 
    10.  
    11.     # start_urls = ['http://tuchong.com/'] 
    12.  
    13.  
    14.  
    15.     def start_requests(self): 
    16.  
    17.         url = 'https://tuchong.com/rest/tags/%s/posts?page=%d&count=20&order=weekly'; 
    18.  
    19.         # 抓取10個頁面,每頁20個圖集 
    20.  
    21.         # 指定 parse 作為回調(diào)函數(shù)并返回 Requests 請求對象 
    22.  
    23.         for page in range(1, 11): 
    24.  
    25.             yield scrapy.Request(url=url % ('美女', page), callback=self.parse) 
    26.  
    27.  
    28.  
    29.     # 回調(diào)函數(shù),處理抓取內(nèi)容填充 TuchongItem 屬性 
    30.  
    31.     def parse(self, response): 
    32.  
    33.         body = json.loads(response.body_as_unicode()) 
    34.  
    35.         items = [] 
    36.  
    37.         for post in body['postList']: 
    38.  
    39.             item = TuchongItem() 
    40.  
    41.             item['type'] = post['type'] 
    42.  
    43.             item['post_id'] = post['post_id'] 
    44.  
    45.             item['site_id'] = post['site_id'] 
    46.  
    47.             item['title'] = post['title'] 
    48.  
    49.             item['url'] = post['url'] 
    50.  
    51.             item['excerpt'] = post['excerpt'] 
    52.  
    53.             item['image_count'] = int(post['image_count']) 
    54.  
    55.             item['images'] = {} 
    56.  
    57.             # 將 images 處理成 {img_id: img_url} 對象數(shù)組 
    58.  
    59.             for img in post.get('images', ''): 
    60.  
    61.                 img_id = img['img_id'] 
    62.  
    63.                 url = 'https://photo.tuchong.com/%s/f/%s.jpg' % (item['site_id'], img_id) 
    64.  
    65.                 item['images'][img_id] = url 
    66.  
    67.  
    68.  
    69.             item['tags'] = [] 
    70.  
    71.             # 將 tags 處理成 tag_name 數(shù)組 
    72.  
    73.             for tag in post.get('tags', ''): 
    74.  
    75.                 item['tags'].append(tag['tag_name']) 
    76.  
    77.             items.append(item) 
    78.  
    79.         return items 

    當(dāng)然如果不用管道直接在 parse 中處理也是一樣的,只不過這樣結(jié)構(gòu)更清晰一些,而且還有功能更多的FilePipelines和ImagePipelines可供使用,process_item將在每一個條目抓取后觸發(fā),同時還有 open_spider 及 close_spider 函數(shù)可以重載,用于處理爬蟲打開及關(guān)閉時的動作。

    注意:管道需要在項目中注冊才能使用,在 settings.py 中添加:

     
     
     
    1. ITEM_PIPELINES = { 
    2.  
    3.     'tuchong.pipelines.TuchongPipeline': 300, # 管道名稱: 運行優(yōu)先級(數(shù)字小優(yōu)先) 
    4.  

    另外,大多數(shù)網(wǎng)站都有反爬蟲的 Robots.txt 排除協(xié)議,設(shè)置 ROBOTSTXT_OBEY = True 可以忽略這些協(xié)議,是的,這好像只是個君子協(xié)定。如果網(wǎng)站設(shè)置了瀏覽器User Agent或者IP地址檢測來反爬蟲,那就需要更高級的Scrapy功能,本文不做講解。

    四、運行

    返回 cmder 命令行進(jìn)入項目目錄,輸入命令:

     
     
     
    1. scrapy crawl photo 

    終端會輸出所有的爬行結(jié)果及調(diào)試信息,并在***列出爬蟲運行的統(tǒng)計信息,例如:

     
     
     
    1. [scrapy.statscollectors] INFO: Dumping Scrapy stats: 
    2.  
    3. {'downloader/request_bytes': 491, 
    4.  
    5.  'downloader/request_count': 2, 
    6.  
    7.  'downloader/request_method_count/GET': 2, 
    8.  
    9.  'downloader/response_bytes': 10224, 
    10.  
    11.  'downloader/response_count': 2, 
    12.  
    13.  'downloader/response_status_count/200': 2, 
    14.  
    15.  'finish_reason': 'finished', 
    16.  
    17.  'finish_time': datetime.datetime(2017, 11, 27, 7, 20, 24, 414201), 
    18.  
    19.  'item_dropped_count': 5, 
    20.  
    21.  'item_dropped_reasons_count/DropItem': 5, 
    22.  
    23.  'item_scraped_count': 15, 
    24.  
    25.  'log_count/DEBUG': 18, 
    26.  
    27.  'log_count/INFO': 8, 
    28.  
    29.  'log_count/WARNING': 5, 
    30.  
    31.  'response_received_count': 2, 
    32.  
    33.  'scheduler/dequeued': 1, 
    34.  
    35.  'scheduler/dequeued/memory': 1, 
    36.  
    37.  'scheduler/enqueued': 1, 
    38.  
    39.  'scheduler/enqueued/memory': 1, 
    40.  
    41.  'start_time': datetime.datetime(2017, 11, 27, 7, 20, 23, 867300)} 

    主要關(guān)注ERROR及WARNING兩項,這里的 Warning 其實是不符合條件而觸發(fā)的 DropItem 異常。

    五、保存結(jié)果

    大多數(shù)情況下都需要對抓取的結(jié)果進(jìn)行保存,默認(rèn)情況下 item.py 中定義的屬性可以保存到文件中,只需要命令行加參數(shù) -o {filename} 即可:

     
     
     
    1. scrapy crawl photo -o output.json # 輸出為JSON文件 
    2.  
    3. scrapy crawl photo -o output.csv  # 輸出為CSV文件

    注意:輸出至文件中的項目是未經(jīng)過 TuchongPipeline 篩選的項目,只要在 parse 函數(shù)中返回的 Item 都會輸出,因此也可以在 parse 中過濾只返回需要的項目

    如果需要保存至數(shù)據(jù)庫,則需要添加額外代碼處理,比如可以在 pipelines.py 中 process_item 后添加:

     
     
     
    1. ... 
    2.  
    3.     def process_item(self, item, spider): 
    4.  
    5.         ... 
    6.  
    7.         else: 
    8.  
    9.             print(item['url']) 
    10.  
    11.             self.myblog.add_post(item) # myblog 是一個數(shù)據(jù)庫類,用于處理數(shù)據(jù)庫操作 
    12.  
    13.         return item 
    14.  
    15. ... 

    為了在插入數(shù)據(jù)庫操作中排除重復(fù)的內(nèi)容,可以使用 item[‘post_id’] 進(jìn)行判斷,如果存在則跳過。


    分享文章:基于Python的Scrapy爬蟲入門:代碼詳解
    本文URL:http://www.dlmjj.cn/article/dhioioo.html