25、Python快速開發分佈式搜索引擎Scrapy精講—Requests請求和Response響應介紹

百度雲搜索,搜各種資料:http://www.lqkweb.com

搜網盤,搜各種資料:http://www.swpan.cn

Requests請求

Requests請求就是我們在爬蟲文件寫的Requests()方法,也就是提交一個請求地址,Requests請求是我們自定義的**

Requests()方法提交一個請求

  參數:

  url=  字符串類型url地址

  callback= 回調函數名稱

  method= 字符串類型請求方式,如果GET,POST

  headers= 字典類型的,瀏覽器用戶代理

  cookies= 設置cookies

  meta= 字典類型鍵值對,向回調函數直接傳一個指定值

  encoding= 設置網頁編碼

  priority= 默認爲0,如果設置的越高,越優先調度

  dont_filter= 默認爲False,如果設置爲真,會過濾掉當前url

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request,FormRequest
import re

class PachSpider(scrapy.Spider):                            #定義爬蟲類,必須繼承scrapy.Spider
    name = 'pach'                                           #設置爬蟲名稱
    allowed_domains = ['www.luyin.org/']                    #爬取域名
    # start_urls = ['']                                     #爬取網址,只適於不需要登錄的請求,因爲沒法設置cookie等信息

    header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0'}  #設置瀏覽器用戶代理

    def start_requests(self):    #起始url函數,會替換start_urls
        """第一次請求一下登錄頁面,設置開啓cookie使其得到cookie,設置回調函數"""
        return [Request(
            url='http://www.luyin.org/',
            headers=self.header,
            meta={'cookiejar':1},       #開啓Cookies記錄,將Cookies傳給回調函數
            callback=self.parse
        )]

    def parse(self, response):
        title = response.xpath('/html/head/title/text()').extract()
        print(title)

 image

Response響應

Response響應是由downloader返回的響應

image

Response響應參數
  headers 返回響應頭
  status 返回狀態嗎
  body 返回頁面內容,字節類型
  url 返回抓取url

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request,FormRequest
import re

class PachSpider(scrapy.Spider):                            #定義爬蟲類,必須繼承scrapy.Spider
    name = 'pach'                                           #設置爬蟲名稱
    allowed_domains = ['www.luyin.org/']                    #爬取域名
    # start_urls = ['']                                     #爬取網址,只適於不需要登錄的請求,因爲沒法設置cookie等信息

    header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0'}  #設置瀏覽器用戶代理

    def start_requests(self):    #起始url函數,會替換start_urls
        """第一次請求一下登錄頁面,設置開啓cookie使其得到cookie,設置回調函數"""
        return [Request(
            url='http://www.luyin.org/',
            headers=self.header,
            meta={'cookiejar':1},       #開啓Cookies記錄,將Cookies傳給回調函數
            callback=self.parse
        )]

    def parse(self, response):
        title = response.xpath('/html/head/title/text()').extract()
        print(title)
        print(response.headers)
        print(response.status)
        # print(response.body)
        print(response.url)

image

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