scrapy-splash抓取動態數據例子十六 -开发者知识库
一、介紹
本例子用scrapy-splash爬取梅花網(http://www.meihua.info/a/list/today)的資訊信息,輸入給定關鍵字抓取微信資訊信息。
給定關鍵字:數字;融合;電視
抓取信息內如下:
1、資訊標題
2、資訊鏈接
3、資訊時間
4、資訊來源
二、網站信息
三、數據抓取
針對上面的網站信息,來進行抓取
1、首先抓取信息列表
抓取代碼:sels = site.xpath('//li[@class="item"]')
2、抓取標題
抓取代碼:titles = sel.xpath('.//div[@class="first"]/div[1]/a[1]/text()')
3、抓取鏈接
抓取代碼:url = 'http://www.meihua.info' str(sel.xpath('.//div[@class="first"]/div[1]/a[1]/@href')[0].extract())
4、抓取日期
抓取代碼:strdate = sel.xpath('.//span[@class="desc-font date"]/span/text()')
5、抓取來源
抓取代碼:sources = site.xpath('//a[@rel="nofollow"]/text()')
四、完整代碼
# -*- coding: utf-8 -*- import scrapy from scrapy import Request from scrapy.spiders import Spider from scrapy_splash import SplashRequest from scrapy_splash import SplashMiddleware from scrapy.http import Request, HtmlResponse from scrapy.selector import Selector from scrapy_splash import SplashRequest from scrapy_ott.items import SplashTestItem from scrapy_ott.mongoDB import mongoDbBase import scrapy_ott.IniFile from scrapy_ott.LogFile import LogFile import sys import os import re import time reload(sys) sys.setdefaultencoding('utf-8') # sys.stdout = open('output.txt', 'w') class meihuaSpider(Spider): log = LogFile(time.strftime('%Y-%m-%d') '.txt') name = 'meihua' db = mongoDbBase() configfile = os.path.join(os.getcwd(), 'scrapy_ott\setting.conf') cf = scrapy_ott.IniFile.ConfigFile(configfile) information_wordlist = cf.GetValue("section", "information_keywords").split(';') websearch_urls = cf.GetValue("meihua", "websearchurl").split(';') start_urls = [] for url in websearch_urls: start_urls.append(url) # request需要封裝成SplashRequest def start_requests(self): self.log.WriteLog(u'抓取梅花網資訊數據') for url in self.start_urls: yield SplashRequest(url , self.parse , args={'wait': '2'} ) def Comapre_to_days(self,leftdate, rightdate): ''' 比較連個字符串日期,左邊日期大於右邊日期多少天 :param leftdate: 格式:2017-04-15 :param rightdate: 格式:2017-04-15 :return: 天數 ''' l_time = time.mktime(time.strptime(leftdate, '%Y-%m-%d')) r_time = time.mktime(time.strptime(rightdate, '%Y-%m-%d')) result = int(l_time - r_time) / 86400 return result def date_isValid(self, strDateText): ''' 判斷日期時間字符串是否合法:如果給定時間大於當前時間是合法,或者說當前時間給定的范圍內 :param strDateText: 四種格式 '今天'; '前天' ; '昨天' ;'06月12日 ' :return: True:合法;False:不合法 ''' currentDate = time.strftime('%Y-%m-%d') if strDateText.find('今天') > -1 : return True, currentDate return False, '' def parse(self, response): site = Selector(response) sels = site.xpath('//li[@class="item"]') for sel in sels: strdate = sel.xpath('.//span[@class="desc-font date"]/span/text()') flag, date = self.date_isValid(strdate[0].extract()) if flag: titles = sel.xpath('.//div[@class="first"]/div[1]/a[1]/text()') title = str(titles[0].extract()) url = 'http://www.meihua.info' str(sel.xpath('.//div[@class="first"]/div[1]/a[1]/@href')[0].extract()) for keyword in self.information_wordlist: if title.find(keyword) > -1: yield SplashRequest(url , self.parse_item , args={'wait': '1'}, meta={'date': date, 'url': url, 'keyword': keyword, 'title': title} ) def parse_item(self, response): site = Selector(response) it = SplashTestItem() it['title'] = response.meta['title'] it['url'] = response.meta['url'] it['date'] = response.meta['date'] it['keyword'] = response.meta['keyword'] # sources = site.xpath('//div[@class="art-content"]/p[27]/strong/a/text()') sources = site.xpath('//a[@rel="nofollow"]/text()') if len(sources)>0: it['source'] = sources[0].extract() else: it['source'] = '梅花網' # sources = site.xpath('//div[@style="text-align: center;"]/font/text()') # if len(sources) > 1: # it['source'] = str(sources[1].extract()).replace('消息源:','') # else: # it['source']='梅花網' self.db.SaveInformation(it) return it
最佳答案:
本文经用户投稿或网站收集转载,如有侵权请联系本站。
0条回复