使用splash抓取js動態加載的網頁,輸出網頁源代碼,以html的格式保存到本地,然后編寫個py文件抓取自己想要的信息,又希望自己的抓取方式能夠復用到scrapy-splash爬蟲項目項目中。
可以使用下面的方式抓取本地的html文件:
# -*- coding: utf-8 -*-
# @AuThor : frank_lee
from scrapy.selector import Selector
htmlfile = open("zfcaigou.html", 'r', encoding='utf-8')
htmlhandle = htmlfile.read()
pagedata = Selector(text=htmlhandle)
infodata = pagedata.css(".items p")
for infoline in infodata:
city = infoline.css(".warning::text").extract()[0]
issuescate = infoline.css(".warning .limit::text").extract()[0]
title = infoline.css("a .underline::text").extract()[0]
publish_date = infoline.css(".time::text").extract()[0]
print(city+issuescate+publish_date)
首先說下網頁源代碼的獲?。?br> 下面這張圖,對于已經安裝splash的童鞋應該不陌生,在1處輸入想要抓取的動態網頁的網址,點一下2處。
稍等片刻,網頁的返回結果就會呈現出渲染截圖、HAR加載統計數據和網頁的源代碼。
將上圖中方框內網頁源代碼保存到本地HTML文件里,用瀏覽器打開就可以像正常網頁一樣對其分析,抓取。如果覺得上面方式不夠高級,配置一下scrapy的settings文件,和spiders下的文件只抓網頁也是可以的,像下面這樣,執行下,也會輸出網頁源代碼。
# -*- coding: utf-8 -*-
import scrapy
from scrapy_splash import SplashRequest
class ZfcaigouSpider(scrapy.Spider):
name = 'zfcaigou'
allowed_domains = ['www.zjzfcg.gov.cn']
start_urls = ['http://www.zjzfcg.gov.cn/purchaseNotice/index.html?categoryId=3001']
def start_requests(self):
for url in self.start_urls:
yield SplashRequest(url=url, callback=self.parse,
args={'wait': 1}, endpoint='render.html')
def parse(self, response):
print(response.body.decode("utf-8"))
pass
下面這張圖片就是保存為html文件后 使用pycharm打開的,按下F12就可以對其進行分析了,使用文章開始處的代碼就可以將我們需要的信息通過本地的html文件輸出或保存。