scrapy框架+selenium的使用


scrapy框架+selenium的使用

1 使用情景:   

  在通過scrapy框架進行某些網站數據爬取的時候,往往會碰到頁面動態數據加載的情況發生,如果直接使用scrapy對其url發請求,是絕對獲取不到那部分動態加載出來的數據值。但是通過觀察我們會發現,通過瀏覽器進行url請求發送則會加載出對應的動態加載出的數據。那么如果我們想要在scrapy也獲取動態加載出的數據,則必須使用selenium創建瀏覽器對象,然后通過該瀏覽器對象進行請求發送,獲取動態加載的數據值

 2 使用流程

  1 重寫爬蟲文件的__init__()構造方法,在該方法中使用selenium實例化一個瀏覽器對象(因為瀏覽器對象只需要被實例化一次).

  2 重寫爬蟲文件的closed(self,spider)方法,在其內部關閉瀏覽器對象,該方法是在爬蟲結束時被調用.

  3 重寫下載中間件的process_response方法,讓該方法對響應對象進行攔截,並篡改response中存儲的頁面數據.

  4 在settings配置文件中開啟下載中間件

3 使用案例: 爬取XXX網站新聞的部分板塊內容

  爬蟲文件: 

# 注意:這里對請求進行初始化后,每一次請求都是使用selenium

from selenium import webdriver
from  selenium.webdriver.chrome.options import Options    # 使用無頭瀏覽器
import scrapy
無頭瀏覽器設置
chorme_options = Options()
chorme_options.add_argument("--headless")
chorme_options.add_argument("--disable-gpu")


class WangyiSpider(scrapy.Spider):
    name = 'wangyi'
    # allowed_domains = ['wangyi.com']   # 允許爬取的域名
    start_urls = ['https://news.163.com/']

    # 實例化一個瀏覽器對象
    def __init__(self):
        self.browser = webdriver.Chrome(chrome_options=chorme_options)
        super().__init__()

    def start_requests(self):
        url = "https://news.163.com/"
        response = scrapy.Request(url,callback=self.parse_index)
        yield response

    # 整個爬蟲結束后關閉瀏覽器
    def close(self,spider):
        self.browser.quit()

    # 訪問主頁的url, 拿到對應板塊的response
    def parse_index(self, response):
        div_list = response.xpath("//div[@class='ns_area list']/ul/li/a/@href").extract()
        index_list = [3,4,6,7]
        for index in index_list:
            response = scrapy.Request(div_list[index],callback=self.parse_detail)
            yield response

    # 對每一個板塊進行詳細訪問並解析, 獲取板塊內的每條新聞的url
    def parse_detail(self,response):
        div_res = response.xpath("//div[@class='data_row news_article clearfix ']")
        # print(len(div_res))
        title = div_res.xpath(".//div[@class='news_title']/h3/a/text()").extract_first()
        pic_url = div_res.xpath("./a/img/@src").extract_first()
        detail_url = div_res.xpath("//div[@class='news_title']/h3/a/@href").extract_first()
        infos = div_res.xpath(".//div[@class='news_tag//text()']").extract()
        info_list = []
        for info in infos:
            info = info.strip()
            info_list.append(info)
        info_str = "".join(info_list)
        item = WangyiproItem()

        item["title"] = title
        item["detail_url"] = detail_url
        item["pic_url"] = pic_url
        item["info_str"] = info_str

        yield scrapy.Request(url=detail_url,callback=self.parse_content,meta={"item":item})    # 通過 參數meta 可以將item參數傳遞進 callback回調函數,再由 response.meta[...]取出來

    # 對每條新聞的url進行訪問, 並解析
    def parse_content(self,response):
        item = response.meta["item"]    # 獲取從response回調函數由meta傳過來的 item 值
        content_list = response.xpath("//div[@class='post_text']/p/text()").extract()
        content = "".join(content_list)
        item["content"] = content
        yield item

 


免責聲明!

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



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