Python爬蟲之Scrapy框架使用selenium


在scrapy中使用selenium的編碼流程:

    1.在spider的構造方法中創建一個瀏覽器對象(作為當前spider的一個屬性)
    2.重寫spider的一個方法closed(self,spider),在該方法中執行瀏覽器關閉的操作
    3.在下載中間件的process_response方法中,通過spider參數獲取瀏覽器對象
    4.在中間件的process_response中定制基於瀏覽器自動化的操作代碼(獲取動態加載出來的頁面源碼數據)
    5.實例化一個響應對象,且將page_source返回的頁面源碼封裝到該對象中
    6.返回該新的響應對象

需求 在Scrapy框架中使用selenium來實現編程 網易頁面

wangyi.py

import scrapy
from selenium import webdriver
# 實例化瀏覽器可以通過中間件的process_response中的spider來獲取
#因此實例化瀏覽器可以寫在這里
class WangyiSpider(scrapy.Spider):
    name = 'wangyi'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['http://war.163.com/']
    #實例化瀏覽器對象  只能被調一次
    def __init__(self):
        self.bro = webdriver.Chrome(r'C:\pacong_data\day3\chromedriver.exe')
    #不能寫在這 因為這里也會被調多次
    def parse(self, response):
        div_list = response.xpath('//div[@class="data_row news_article clearfix "]')
        for div in div_list:
            title = div.xpath('.//div[@class="news_title"]/h3/a/text()').extract_first()
            print(title)

    #在整個爬蟲結束之后才會被調用
    def closed(self,spider):
        print('關閉瀏覽器對象')
        self.bro.quit()

middlewares.py

from time import sleep
#1 HtmlResponse是response對應的類
from scrapy.http import HtmlResponse

class WangyiproDownloaderMiddleware(object):
    #攔截響應 重新生成一個新的響應對象 包含動態數據 實例化瀏覽器中不能寫在這 這個方法可能會調多次
    #實例化瀏覽器可以通過中間件的process_response中的spider來獲取
    #這里的request是response中所對應的請求對象
    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        #核心內容  如何獲取動態加載的數據  使用selenium

        #獲取實例化的瀏覽器對象 通過spider來獲取
        #讓這個瀏覽器發送get請求  是請求的url
        #也就是wangyi.py中的start_urls = ['http://war.163.com/']  這個url
        print('即將返回一個新的響應對象')
        bro = spider.bro
        bro.get(url=request.url)
        #注意 這兩個寫法是一致的
        # bro.get(url='http://war.163.com/')
        # bro.get(url=spider.bro.current_url)
        sleep(3)
        #包含了動態加載出來的數據   獲取到頁面源碼數據
        page_text = bro.page_source
        #body 響應體

        return HtmlResponse(url=request.url,body=page_text,encoding='utf-8',request=request)

settings.py

BOT_NAME = 'wangyiPro'

SPIDER_MODULES = ['wangyiPro.spiders']
NEWSPIDER_MODULE = 'wangyiPro.spiders'

USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'wangyiPro (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

DOWNLOADER_MIDDLEWARES = {
   'wangyiPro.middlewares.WangyiproDownloaderMiddleware': 543,
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM