一、介绍
本例子用scrapy-splash抓取活动行网站给定关键字抓取活动信息。
给定关键字:数字;融合;电视
抓取信息内如下:
1、资讯标题
2、资讯链接
3、资讯时间
4、资讯来源
二、网站信息
三、数据抓取
针对上面的网站信息,来进行抓取
1、首先抓取信息列表
抓取代码:sels = site.xpath('//ul[@class="event-horizontal-list-new"]/li')
2、抓取标题
抓取代码:title = str(sel.xpath('.//h3/a/text()')[0].extract())
3、抓取链接
抓取代码:url = 'http://www.huodongxing.com' + str(sel.xpath('.//a/@href')[0].extract())
4、抓取日期
抓取代码:dates = sel.xpath('.//div[1]/text()')
5、主办方
抓取代码:organizers = sel.xpath('.//div[3]/a[2]/span/text()')
6、地点
抓取代码:areas = site.xpath('.//div[@class="address"]/a/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 SplashMeetingItem 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') import urllib # sys.stdout = open('output.txt', 'w') class huodongxingSpider(Spider): log = LogFile(time.strftime('%Y-%m-%d') + '.txt') name = 'huodongxing' db = mongoDbBase() configfile = os.path.join(os.getcwd(), 'scrapy_ottsetting.conf') cf = scrapy_ott.IniFile.ConfigFile(configfile) meeting_wordlist = cf.GetValue("section", "meeting_keywords").split(';') websearch_url = cf.GetValue("huodongxing", "websearchurl") start_urls = [] for keyword in meeting_wordlist: url = websearch_url + '&pi='+ str(1)+ '&qs=' +keyword start_urls.append(url) # request需要封装成SplashRequest def start_requests(self): self.log.WriteLog(u'抓取活动行网站数据') for url in self.start_urls: index = url.rfind('=') yield SplashRequest(url , self.parse , args={'wait': '2'}, meta={'keyword': url[index + 1:]} ) 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: 四种格式 '2小时前'; '2天前' ; '昨天' ;'2017.2.12 ' :return: True:合法;False:不合法 ''' currentDate = time.strftime('%Y-%m-%d') datePattern = re.compile(r'd{4}-d{1,2}-d{1,2}') strDate = re.findall(datePattern, strDateText) if len(strDate) == 1: if self.Comapre_to_days(strDate[0],currentDate)>0: return True,strDate[0] return False, '' def parse(self, response): site = Selector(response) sels = site.xpath('//ul[@class="event-horizontal-list-new"]/li') keyword = response.meta['keyword'] for sel in sels: dates = sel.xpath('.//div[1]/text()') if len(dates) > 0: strdate = str(dates[1].extract()) flag, date = self.date_isValid(strdate) if flag: title = str(sel.xpath('.//h3/a/text()')[0].extract()) if title.find(keyword) > -1: url = 'http://www.huodongxing.com' + str(sel.xpath('.//a/@href')[0].extract()) organizers = sel.xpath('.//div[3]/a[2]/span/text()') if len(organizers)>0: organizer = organizers[0].extract() yield SplashRequest(url , self.parse_item , args={'wait': '1'}, meta={'date': date, 'url': url, 'keyword': keyword, 'title': title,'organizer':organizer} ) def parse_item(self, response): site = Selector(response) it = SplashMeetingItem() it['title'] = response.meta['title'] it['url'] = response.meta['url'] it['date'] = response.meta['date'] it['keyword'] = response.meta['keyword'] it['startdate'] = response.meta['date'] it['enddate'] = response.meta['date'] it['organizer'] = response.meta['organizer'] dates=site.xpath('.//div[@class="media-body"]/div[1]/text()|.//div[@class="media-body"]/div[1]/em/text()') if len(dates)>0: print dates[0].extract() # it['date'] = dates[0].extract() areas = site.xpath('.//div[@class="address"]/a/text()') if len(areas) > 0: it['area'] = areas[0].extract() self.db.SaveMeeting(it) return it