一、介绍

    本例子用scrapy-splash抓取今日头条网站给定关键字抓取咨询信息。

    给定关键字:打通;融合;电视

    抓取信息内如下:

      1、资讯标题

      2、资讯链接

      3、资讯时间

      4、资讯来源

  二、网站信息

    

    

    

    

  三、数据抓取

    针对上面的网站信息,来进行抓取

    1、首先抓取信息列表

      抓取代码:sels = site.xpath('//div[@class="articleCard"]')

    2、抓取标题

      由于在抓取标题的时候,在列表页不太好抓取,所以就绕了一下直接每条资讯的链接页面来抓取标题

      抓取代码:titles = sel.xpath('.//div[@class="doc-title"]/text()')

    3、抓取链接

      抓取代码:url = 'http://www.toutiao.com' + str(sel.xpath('.//a[@class="link title"]/@href')[0].extract())

    4、抓取日期

      抓取代码:dates = sel.xpath('.//span[@class="lbtn"]/text()')

    5、抓取来源

      抓取代码:source=str(sel.xpath('.//a[@class="lbtn source J_source"]/text()')[0].extract())

  

  四、完整代码

    1、toutiaoSpider

# -*- 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 splash_test.items import SplashTestItem
import IniFile
import sys
import os
import re
import time reload(sys)
sys.setdefaultencoding('utf-8') # sys.stdout = open('output.txt', 'w') class toutiaoSpider(Spider):
name = 'toutiao' configfile = os.path.join(os.getcwd(), 'splash_test\spiders\setting.conf') cf = IniFile.ConfigFile(configfile)
information_keywords = cf.GetValue("section", "information_keywords")
information_wordlist = information_keywords.split(';')
websearchurl = cf.GetValue("toutiao", "websearchurl")
start_urls = []
for word in information_wordlist:
start_urls.append(websearchurl + word) # request需要封装成SplashRequest
def start_requests(self):
for url in self.start_urls:
index = url.rfind('=')
yield SplashRequest(url
, self.parse
, args={'wait': ''},
meta={'keyword': url[index + 1:]}
) def date_isValid(self, strDateText):
'''
判断日期时间字符串是否合法:如果给定时间大于当前时间是合法,或者说当前时间给定的范围内
:param strDateText: 四种格式 '2小时前'; '2天前' ; '昨天' ;'2017.2.12 '
:return: True:合法;False:不合法
'''
currentDate = time.strftime('%Y-%m-%d')
if strDateText.find('分钟前') > 0 or strDateText.find('刚刚') > -1:
return True, currentDate
elif strDateText.find('小时前') > 0:
datePattern = re.compile(r'\d{1,2}')
ch = int(time.strftime('%H')) # 当前小时数
strDate = re.findall(datePattern, strDateText)
if len(strDate) == 1:
if int(strDate[0]) <= ch: # 只有小于当前小时数,才认为是今天
return True, currentDate
return False, '' def parse(self, response):
site = Selector(response)
# it_list = []
keyword = response.meta['keyword']
sels = site.xpath('//div[@class="articleCard"]')
for sel in sels:
dates = sel.xpath('.//span[@class="lbtn"]/text()')
if len(dates) > 0:
flag, date = self.date_isValid(dates[0].extract())
if flag:
url = 'http://www.toutiao.com' + str(sel.xpath('.//a[@class="link title"]/@href')[0].extract())
source=str(sel.xpath('.//a[@class="lbtn source J_source"]/text()')[0].extract())
yield SplashRequest(url
, self.parse_item
, args={'wait': ''},
meta={'date': date, 'url': url,
'keyword': keyword, 'source': source}
) def parse_item(self, response):
site = Selector(response)
it = SplashTestItem()
titles = site.xpath('//h1[@class="article-title"]/text()')
count = 0
if len(titles) > 0:
keyword = response.meta['keyword']
strtiltle = str(titles[0].extract())
if strtiltle.find(keyword) > -1:
it['title'] = strtiltle
it['url'] = response.meta['url']
it['date'] = response.meta['date']
it['keyword'] = keyword
it['source'] = response.meta['source']
return it

    2、SplashTestItem

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html import scrapy class SplashTestItem(scrapy.Item):
#标题
title = scrapy.Field()
#日期
date = scrapy.Field()
#链接
url = scrapy.Field()
#关键字
keyword = scrapy.Field()
#来源网站
source = scrapy.Field()

    3、SplashTestPipeline

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import codecs
import json class SplashTestPipeline(object):
def __init__(self):
# self.file = open('data.json', 'wb')
self.file = codecs.open(
'spider.txt', 'w', encoding='utf-8')
# self.file = codecs.open(
# 'spider.json', 'w', encoding='utf-8') def process_item(self, item, spider):
line = json.dumps(dict(item), ensure_ascii=False) + "\n"
self.file.write(line)
return item def spider_closed(self, spider):
self.file.close()

    4、setting.conf

iedriverserver = C:\Program Files\Internet Explorer\IEDriverServer.exe
meeting_keywords = 互联网电视;智能电视;数字;影音;家庭娱乐;节目;视听;版权;数据
information_keywords = 电视;数字电视;OTT;节目内容;盒子;智能推荐;个性化;视频;影音;跨屏;融合;打通;多平台
#information_keywords = 电视;OTT
invalid_day = 4
nexturllabel = 下一页
timesleep = 3
[toutiao] websearchurl = http://www.toutiao.com/search/?keyword=

scrapy-splash抓取动态数据例子三的更多相关文章

  1. scrapy-splash抓取动态数据例子一

    目前,为了加速页面的加载速度,页面的很多部分都是用JS生成的,而对于用scrapy爬虫来说就是一个很大的问题,因为scrapy没有JS engine,所以爬取的都是静态页面,对于JS生成的动态页面都无 ...

  2. scrapy-splash抓取动态数据例子八

    一.介绍 本例子用scrapy-splash抓取界面网站给定关键字抓取咨询信息. 给定关键字:个性化:融合:电视 抓取信息内如下: 1.资讯标题 2.资讯链接 3.资讯时间 4.资讯来源 二.网站信息 ...

  3. scrapy-splash抓取动态数据例子七

    一.介绍 本例子用scrapy-splash抓取36氪网站给定关键字抓取咨询信息. 给定关键字:个性化:融合:电视 抓取信息内如下: 1.资讯标题 2.资讯链接 3.资讯时间 4.资讯来源 二.网站信 ...

  4. scrapy-splash抓取动态数据例子六

    一.介绍 本例子用scrapy-splash抓取中广互联网站给定关键字抓取咨询信息. 给定关键字:打通:融合:电视 抓取信息内如下: 1.资讯标题 2.资讯链接 3.资讯时间 4.资讯来源 二.网站信 ...

  5. scrapy-splash抓取动态数据例子五

    一.介绍 本例子用scrapy-splash抓取智能电视网网站给定关键字抓取咨询信息. 给定关键字:打通:融合:电视 抓取信息内如下: 1.资讯标题 2.资讯链接 3.资讯时间 4.资讯来源 二.网站 ...

  6. scrapy-splash抓取动态数据例子四

    一.介绍 本例子用scrapy-splash抓取微众圈网站给定关键字抓取咨询信息. 给定关键字:打通:融合:电视 抓取信息内如下: 1.资讯标题 2.资讯链接 3.资讯时间 4.资讯来源 二.网站信息 ...

  7. scrapy-splash抓取动态数据例子二

    一.介绍 本例子用scrapy-splash抓取一点资讯网站给定关键字抓取咨询信息. 给定关键字:打通:融合:电视 抓取信息内如下: 1.资讯标题 2.资讯链接 3.资讯时间 4.资讯来源 二.网站信 ...

  8. scrapy-splash抓取动态数据例子十六

    一.介绍 本例子用scrapy-splash爬取梅花网(http://www.meihua.info/a/list/today)的资讯信息,输入给定关键字抓取微信资讯信息. 给定关键字:数字:融合:电 ...

  9. scrapy-splash抓取动态数据例子十五

    一.介绍 本例子用scrapy-splash爬取电视之家(http://www.tvhome.com/news/)网站的资讯信息,输入给定关键字抓取微信资讯信息. 给定关键字:数字:融合:电视 抓取信 ...

随机推荐

  1. pc、移动端H5网站 QQ在线客服、群链接代码【我和qq客服的那些事儿】

    转载:http://blog.csdn.net/fungleo/article/details/51835368#comments 移动端H5 QQ在线客服链接代码 <a href=" ...

  2. php api接口校验规则示例

    1.发送 /** * 客户端请求 * @param url 接口地址 * @param array $params(post) * @return json * @throws Exception * ...

  3. sql几种删除语句的联系与区别

    DELETE.TRUNCATE.DROP三种删除语句联系与区别 相同点: 1.truncate和不带where子句的delete.以及drop都会删除表内的数据. 2.drop.truncate都是D ...

  4. vim的保存文件和退出命令

    文章来源:http://blog.sina.com.cn/s/blog_5e357d2d0100zmth.html 命令 简单说明 :w 保存编辑后的文件内容,但不退出vim编辑器.这个命令的作用是把 ...

  5. 17-7-24-react入门

    先说明下为什么说好每天一更,周五周六周日都没有更新.因为在周五的时候,上司主动找我谈了转正后的工资4-4.5K.本来想好是6K的,后来打听了一圈公司的小伙伴,都是5-5.5,我就把自己定到了5K.万万 ...

  6. Linux中的命令判断

    命令判断会用到三个特殊符号分号(;),&&,|| (1).分号(;) 不考虑命令的相关性,连续执行,不保证命令全部执行成功. 例: [root@xuexi ~]# ls xxxx ; ...

  7. 解决vscode按下ctrl+S的时候自动格式化

    按下ctrl+S的时候自动格式化 为什么需要这种操作? 优点: 保存的时候格式化,让我们的代码自动格式化,减少人工调整. 缺点: 有一些打好包的JS有时候修改一下,但不需要格式化,因为打好包就是要压缩 ...

  8. BZOJ 2242 [SDOI2011]计算器(快速幂+Exgcd+BSGS)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=2242 [题目大意] 给出T和K 对于K=1,计算 Y^Z Mod P 的值 对于K=2 ...

  9. 【区间dp】【记忆化搜索】UVALive - 3516 - Exploring Pyramids

    f(i,j)=sum(f(i+1,k-1)*f(k,j) | i+2<=k<=j,Si=Sk=Sj). f(i+1,k-1)是划分出第一颗子树,f(k,j)是划分出剩下的子树. #incl ...

  10. 【c++随手记】编程基础之输入输出

    今天试了下noi oj的1.1节,随便总结一下. [cout左对齐右对齐的方法] #include<iostream> #include<cstdio> #include< ...