Python爬蟲開發【第1篇】【Scrapy入門】

來源:互聯網
上載者:User

標籤:item   append   note   str   約束   個人資訊   建立項目   http   The   

Scrapy的安裝介紹

Scrapy架構官方網址:http://doc.scrapy.org/en/latest

Scrapy中文維護網站:http://scrapy-chs.readthedocs.io/zh_CN/latest/index.html

Windows 安裝方式
  • Python 2 / 3
  • 升級pip版本:pip install --upgrade pip
  • 通過pip 安裝 Scrapy 架構pip install Scrapy

具體Scrapy安裝流程參考:http://doc.scrapy.org/en/latest/intro/install.html#intro-install-platform-notes

目標
  • 建立一個Scrapy項目
  • 定義提取的結構化資料(Item)
  • 編寫爬取網站的 Spider 並提取出結構化資料(Item)
  • 編寫 Item Pipelines 來儲存提取到的Item(即結構化資料)
1.建立項目(scrapy startproject)
  • 在開始爬取之前,必須建立一個新的Scrapy項目。進入自訂的項目目錄中,運行下列命令:
  • scrapy startproject mySpider
  • 建立項目mySpider,目錄及主要檔案作用:
    • scrapy.cfg :項目的設定檔
    • mySpider/ :項目的Python模組,將會從這裡引用代碼

    • mySpider/items.py :項目的目標檔案

    • mySpider/pipelines.py :項目的管道檔案

    • mySpider/settings.py :項目的設定檔案mySpider/spiders/ :儲存爬蟲代碼目錄

2.明確目標(mySpider/items.py)

目標:抓取http://www.itcast.cn/channel/teacher.shtml 網站裡的所有講師的姓名、職稱和個人資訊

步驟:

  1. 開啟mySpider目錄下的items.py

  2. Item 定義結構化資料欄位,用來儲存爬取到的資料,有點像Python中的dict,但是提供了一些額外的保護減少錯誤。

  3. 可以通過建立一個 scrapy.Item 類, 並且定義類型為 scrapy.Field的類屬性來定義一個Item(可以理解成類似於ORM的映射關係)。

  4. 接下來,建立一個ItcastItem 類,和構建item模型(model)。

import scrapyclass ItcastItem(scrapy.Item):    name = scrapy.Field()    level = scrapy.Field()    info = scrapy.Field()
3.製作爬蟲 (spiders/itcastSpider.py)

①.爬資料

 在目前的目錄下輸入命令,將在mySpider/spider目錄下建立一個名為itcast的爬蟲,並指定爬取域的範圍:

scrapy genspider itcast "itcast.cn"  

 開啟 mySpider/spider目錄裡的 itcast.py,預設增加了下列代碼:

import scrapyclass ItcastSpider(scrapy.Spider):    name = "itcast"    allowed_domains = ["itcast.cn"]    start_urls = (        ‘http://www.itcast.cn/‘,    )    def parse(self, response):        pass

要建立一個Spider, 須用scrapy.Spider類建立一個子類,並確定了三個強制的屬性 和 一個方法。

  A:name = "" ,爬蟲的識別名稱,必須是唯一的,在不同的爬蟲必須定義不同的名字。

  B:allow_domains = [] ,搜尋的網域名稱範圍,即爬蟲的約束地區,規定爬蟲只爬不存在的URL會被忽略。

  C:start_urls = () ,爬取的URL元組/列表。

    爬蟲從這裡開始抓取資料,所以,第一次下載的資料將會從這些urls開始。其他子URL將會從這些起始URL中繼承性產生。

  D:parse(self, response),解析方法,每個初始URL完成下載後將被調用,調用的時候傳入從每一個URL傳回的Response對象來作為唯一參數,主要作用如下:

    • 負責解析返回的網頁資料(response.body),提取結構化資料(產生item)
    • 產生需要下一頁的URL請求。
將start_urls的值修改為需要爬取的第一個url
start_urls = ("http://www.itcast.cn/channel/teacher.shtml",)
修改parse()方法
def parse(self, response):    filename = "teacher.html"    open(filename, ‘w‘).write(response.body)
運行程式,即可得到爬取的網頁資訊

 

②.取資料

 爬取整個網頁完畢,接下來的就是取資料

 觀察網頁源碼樣式,選擇合適方法提取資料

 將之前在mySpider/items.py 裡定義的ItcastItem類引入 :

from mySpider.items import ItcastItem

 將得到的資料封裝到一個 ItcastItem 對象中,可以儲存每個老師的屬性: 

from mySpider.items import ItcastItemdef parse(self, response):    #open("teacher.html","wb").write(response.body).close()    # 存放老師資訊的集合    items = []    for each in response.xpath("//div[@class=‘li_txt‘]"):        # 將我們得到的資料封裝到一個 `ItcastItem` 對象        item = ItcastItem()        #extract()方法返回的都是unicode字串        name = each.xpath("h3/text()").extract()        title = each.xpath("h4/text()").extract()        info = each.xpath("p/text()").extract()        #xpath返回的是包含一個元素的列表        item[‘name‘] = name[0]        item[‘title‘] = title[0]        item[‘info‘] = info[0]        items.append(item)    # 直接返回最後資料    return items

③.儲存資料 

scrapy儲存資訊的最簡單的方法主要有四種,-o 輸出指定格式的檔案,,命令如下:
# json格式,預設為Unicode編碼scrapy crawl itcast -o teachers.json# json lines格式,預設為Unicode編碼scrapy crawl itcast -o teachers.jsonl# csv 逗號運算式,可用Excel開啟scrapy crawl itcast -o teachers.csv# xml格式scrapy crawl itcast -o teachers.xml

  

 

Python爬蟲開發【第1篇】【Scrapy入門】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.