scrapy 解析xml格式的資料
阿新 • • 發佈:2022-04-07
XMLFeedSpider 主要用於 解析 xml格式的資料
建立一個scrapy 框架
scrapy startproject xxx
建立一個spider
scrapy genspider -t xmlfeed ZhaoYuanCity_2_GovPro(名字) xxx.com(網站名)
解析的例子為招遠市人民政府的資料
""" 招遠市人民政府 """ import re import scrapy from scrapy.spiders import XMLFeedSpider from curreny.items import CurrenyItem class Zhaoyuancity2GovproSpider(XMLFeedSpider): name= 'ZhaoYuanCity_2_GovPro' # allowed_domains = ['xxx.com'] start_urls = ['http://www.zhaoyuan.gov.cn/module/web/jpage/dataproxy.jsp?page=1&webid=155&path=http://www.zhaoyuan.gov.cn/&columnid=48655&unitid=180549&webname=%25E6%258B%259B%25E8%25BF%259C%25E5%25B8%2582%25E6%2594%25BF%25E5%25BA%259C&permiss'] iterator = 'iternodes' # you can change this; see the docs itertag = 'datastore' # change it accordingly def parse_node(self, response, selector): # 用css 獲取 一個列表 source_list = selector.css('recordset record::text').extract() for li in source_list:# 用正則解析url 我們去裡面獲取時間標題和內容 url= re.search(r'href=\"(.*\.html)\"',li).group(1) yield scrapy.Request( url=url, callback=self.parse ) def parse(self,response): # 呼叫item item = CurrenyItem() # 寫入連結提取器中獲取到的url item['title_url'] = response.url # 標題名 item['title_name'] = response.css('meta[name="ArticleTitle"]::attr(content)').get() # 標題時間 item['title_date'] = response.css('meta[name="pubdate"]::attr(content)').get() # 內容提取 含原始碼 item['content_html'] = response.css('.main').get() # 目錄地址為 item['site_path_url'] = "http://www.zhaoyuan.gov.cn/col/col48655/index.html?number=ZYC120106" # 交給item處理 yield item
執行專案
scrapy crawl ZhaoYuanCity_2_GovPro --nolog
解釋——總結:
-
iterator屬性:設定使用的迭代器,預設為“iternodes”(一個基於正則表示式的高效能迭代器),除此之外還有“html”和“xml”迭代器;
-
itertag:設定開始迭代的節點;
-
parse_node方法:在節點與所提供的標籤名相符合時被呼叫,在其中定義資訊提取和處理的操作;
-
namespaces屬性:以列表形式存在,主要定義在文件中會被蜘蛛處理的可用命令空間;
-
parse方法: 解析資料 發起正常請求
-
**adapt_response(response)方法:在spider分析響應前被呼叫;
-
**process_results(response, results)方法:在spider返回結果時被呼叫,主要對結果在返回前進行最後的處理。