Scrapy爬蟲筆記——1

1、安裝:使用pip install scrapy;

假如使用了Fiddler作爲代理服務器進行調試分析,爲了避免該軟件的影響:

打開Fiddler,進入“Tools——>Fiddler Options——>Connections”,將“Act as system proxy on startup”和“Monitor all connections”的勾選取消。

2、(1)、使用命令“scrapy startproject 項目名”創建一個項目;

--logfile=FILE 參數指定日誌文件,在startproject和項目名之間

--loglevel=LEVEL 主要控制日誌信息的等級

從高到低依次爲CRICAL(生嚴重的錯誤),ERROR(發生了必須立即處理的錯誤),WARNING(出現了一些警告信息,即存在潛在的錯誤),INFO(輸出一些提示信息),DEBUG(輸出一些調試信息,常用於開發階段)

--nolog參數可以控制不輸出日誌信息

(2)、命令“cd 爬蟲項目所在目錄”,使用genspider命令創建Scrapy爬蟲文件steve,定義爬取www.sina.com。

scrapy genspider -t basic steve www.sina.com

爬蟲模版有:basic、crawl、csvfeed、xmlfeed。

3、項目目錄結構:

scrapy.cfg 是爬蟲項目的配置文件

items.py 爬蟲項目的數據容器文件,定義我們獲取的數據

pipelines.py 管道文件,對items中定義的數據進一步加工與處理

setting.py 設置文件

spider文件夾下放置爬蟲部分文件

(1)在items中數據以字典形式儲存

(2)spider中的常用屬性和方法:

start_requests() 該方法默認讀取start_urls屬性中定義的網址,爲每一個網址生成一個Request請求對象,並返回迭代對象

make_requests_from_url(url) 該方法會被start_requests() 調用,負責實現生成Request請求對象

closed(reason) 關閉Spider時,該方法被調用

3、Spider的編寫

(1)、

#steve.py
import scrapy
from firstpjt.items import FirstpjtItem

class SteveSpider(scrapy.Spider):
    name = 'steve'
    allowed_domains = ['www.sina.com']
    start_urls = (
        'http://news.sina.com.cn/c/2018-08-12/doc-ihhqtawx1023013.shtml',
        'http://sports.sina.com.cn/basketball/nba/2018-08-12/doc-ihhqtawx1782775.shtml',
        'http://news.sina.com.cn/w/2018-08-12/doc-ihhqtawx0403181.shtml'
    )

    def parse(self, response):
        item = FirstpjtItem()
        item["urlname"]=response.xpath("/html/head/title/text()")
        print(item["urlname"])

運行結果:

(2)、start_urls爲默認的起始網址,通過重寫start_requests()方法實現自定義起始網址:

# steve.py
# -*- coding: utf-8 -*-
import scrapy

from firstpjt.items import FirstpjtItem


class SteveSpider(scrapy.Spider):
    name = 'steve'
    #allowed_domains = ['www.sina.com']
    start_urls = (
        'http://news.sina.com.cn/c/2018-08-12/doc-ihhqtawx1023013.shtml',
        'http://sports.sina.com.cn/basketball/nba/2018-08-12/doc-ihhqtawx1782775.shtml',
        'http://news.sina.com.cn/w/2018-08-12/doc-ihhqtawx0403181.shtml'
    )

    # 自定義起始網址
    urls2 = (
        'https://www.csdn.net/',
        'http://www.ifeng.com/',
        'https://www.suning.com/?utm_source=hao123&utm_medium=mingzhan'
    )

    # 重寫start_requests()方法
    def start_requests(self):
        for url in self.urls2:
            # 調用默認self.make_requests_from_url(url)方法生成具體請求並通過yield返回
            yield self.make_requests_from_url(url)

    def parse(self, response):
        item = FirstpjtItem()
        item["urlname"] = response.xpath("/html/head/title/text()")
        print(item["urlname"])

運行結果:

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