南燕新闻自动生成软件——scrapy爬虫程序

使用scrapy爬虫框架爬取北京大汇丰商学院的新闻,新闻网址:

1.定义Item.py容器类文件,代码如下:

import scrapy


class PhbsNewsItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    date = scrapy.Field()
    origin = scrapy.Field()
    clicks = scrapy.Field()
    content = scrapy.Field()


2.编写spider爬虫文件:

其中,29-35行代码,通过模拟js的点击操作,获取新闻的点击数;

获取如下信息:“$('#todaydowns').html('4');$('#weekdowns').html('6');$('#monthdowns').html('243');$('#hits').html('271');

使用split(“\’ ”)[-2]函数通过单引号拆分,并去倒数第二个数字

import scrapy
import re
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from PHBS_News.items import PhbsNewsItem
from bs4 import BeautifulSoup
import urllib2
import sys
reload(sys)
sys.setdefaultencoding('utf8')

class PhbsNewsSpider(CrawlSpider):
    name = 'PhbsNews'
    allowed_domains = ['www.phbs.pku.edu.cn']
    start_urls = ['http://www.phbs.pku.edu.cn/list-419-1.html']

    rules = [Rule(SgmlLinkExtractor(allow=['http://www.phbs.pku.edu.cn/list-419-\d*.html'])),
             Rule(SgmlLinkExtractor(allow=['http://www.phbs.pku.edu.cn/content-419']), 'parse_torrent')]

    def parse_torrent(self, response):
        soup = BeautifulSoup(response.body)
        #print soup
        title = soup.find(attrs={'class':'title'}).string
        #print title
        date = soup.find(attrs={'class':'inputtime'}).string
        #print date
        orgin = soup.find(attrs={'class':'username'}).string
        #print orgin
        clicks_url = soup.find(attrs={'language':'JavaScript'})['src']
        #print clicks_url

		#获取页面点击数,通过打开js调用的连接
        response = urllib2.urlopen(clicks_url)
        clicks = response.read().split('\'')[-2]
        #print clicks
        content = soup.find(attrs={'class':'content'})
        #print content
        #建立数据库时指定编码为utf-8,此处需统一编码
        items = PhbsNewsItem()
        items['title'] = title.encode('utf-8')
        items['date'] = date
        items['origin'] = orgin
        items['clicks'] = clicks
        items['content'] = content
        #print items
        return items


3.编写pipline存储文件:

import MySQLdb
import MySQLdb.cursors
from scrapy import log
import time
import sys
reload(sys)
sys.setdefaultencoding('utf8')

class PhbsNewsPipeline(object):

    #init只执行一次
    def __init__(self):

        self.db = MySQLdb.connect("localhost","root","","opensns", charset = 'utf8')
        self.cursor = self.db.cursor()

        sql_checkDate = "select create_time from news where category=3 order by create_time desc limit 1"
        self.cursor.execute(sql_checkDate)
        result = self.cursor.fetchall()
        if (result):
            self.latest_date = result[0][0]
        else:
            self.latest_date = 0

    #pipeline默认调用
    def process_item(self, item, spider):

        #将datetime转换为时间戳:
        a = item['date'];
        #将其转换为时间数组
        timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
        #转换为时间戳
        timeStamp = int(time.mktime(timeArray))

        if (timeStamp > self.latest_date):

            sql = "INSERT INTO news(uid, title, category, status, view, dead_line, create_time) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')" % ('1', item['title'], '3', '1', item['clicks'] ,'2147483640', timeStamp)
            
            try:
               # 执行sql语句
               self.cursor.execute(sql)
               print 'herhehrherhehrherherheh'
               
               print int(self.cursor.lastrowid)

               sql_detail = "INSERT INTO news_detail(news_id, content) VALUES (%d, '%s')" % (int(self.cursor.lastrowid), item['content'])
               self.cursor.execute(sql_detail)

               # 提交到数据库执行
               self.db.commit()
            except:
               # Rollback in case there is any error
               self.db.rollback()

        return item

    def handle_error(self, e):
        log.err(e)

4.最后,不要忘记在setting文件中添加:

BOT_NAME = 'PHBS_News'

SPIDER_MODULES = ['PHBS_News.spiders']
NEWSPIDER_MODULE = 'PHBS_News.spiders'

ITEM_PIPELINES = {  
    #'importantNews.pipelines.ImportantnewsPipeline':300, 
    'PHBS_News.pipelines.PhbsNewsPipeline':300
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
新闻稿在线发布系统是一套帮助企业和个人发布新闻稿、新闻稿排名优化、加入新闻源的营销系统。 新闻稿在线发布系统具有以下特点: 1、分秒之间把新闻迅速精准的传播出去,确保新闻时效性、客户人群准确性。 2、门户网站、行业权威网站的新闻报道,让您的企业(品牌)美誉度、消费者认可度迅速提高。 3、第一时间出现在Google、百度、雅虎、搜搜、搜狗、有道等搜索引擎的搜索结果中,并使新闻的排名靠前。 4、如果企业出现公关危机或者网络负面信息,可以快速有效地传播正面信息,击破压制污蔑谣言,轻松化解企业危机。 5、新闻营销覆盖的行业:IT、财经、快消、女性、时尚、服装、育婴、汽车、健康、体育、建材、家居、厨卫、五金、数码、家电、通讯、珠宝、娱乐、旅游等 新闻稿营销的作用分析: 第一、高质量的新闻稿件,能够获得在这些大型新闻网站首页展示的机会,这些新闻网站每日的访问量大的惊人,恐怕传统的电视广告,都不具备与这种互联网媒体相媲美的能力。 第二、通过为互联网新闻工作者提供新闻素材,使得自己公司的品牌形象传播到互联网的各个角落。 第三、高质量的新闻稿件,可以获得互联网有效的转载,通过在新闻稿件中增加版权,文章出处,可以获得高质量的网站外链,有效帮助自己网站在搜索引擎中关键词排名的提升。 第四、高质量的新闻稿件,可以吸引更多的阅读者,关注您的网站。 第五、在这些阅读者中,有很大一部分,应该是您的潜在客户。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值