python抓取最新博客内容并生成Rss

yipeiwu_com5年前Python爬虫

osc的rss不是全文输出的,不开心,所以就有了python抓取osc最新博客生成Rss

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


from bs4 import BeautifulSoup
import urllib2

import datetime
import time
import PyRSS2Gen
from email.Utils import formatdate
import re
import sys
import os
reload(sys)
sys.setdefaultencoding('utf-8')

class RssSpider():
 def __init__(self):
 self.myrss = PyRSS2Gen.RSS2(title='OSChina',
link='http://my.oschina.net',
description=str(datetime.date.today()),
pubDate=datetime.datetime.now(),
 lastBuildDate = datetime.datetime.now(),
items=[]
)
self.xmlpath=r'/var/www/myrss/oschina.xml'

self.baseurl="http://www.oschina.net/blog"
 #if os.path.isfile(self.xmlpath):
#os.remove(self.xmlpath)
 def useragent(self,url):
 i_headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) 
 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36", 
"Referer": 'http://baidu.com/'}
 req = urllib2.Request(url, headers=i_headers)
 html = urllib2.urlopen(req).read()
 return html
 def enterpage(self,url):
 pattern = re.compile(r'd{4}Sd{2}Sd{2}sd{2}Sd{2}')
rsp=self.useragent(url)
soup=BeautifulSoup(rsp)
timespan=soup.find('div',{'class':'BlogStat'})
timespan=str(timespan).strip().replace('n','').decode('utf-8')
match=re.search(r'd{4}Sd{2}Sd{2}sd{2}Sd{2}',timespan)
timestr=str(datetime.date.today())
 if match:
timestr=match.group()
 #print timestr
ititle=soup.title.string
div=soup.find('div',{'class':'BlogContent'})
rss=PyRSS2Gen.RSSItem(
title=ititle,
link=url,
 description = str(div),
 pubDate = timestr
)

 return rss
 def getcontent(self):
rsp=self.useragent(self.baseurl)
soup=BeautifulSoup(rsp)
ul=soup.find('div',{'id':'RecentBlogs'})
 for li in ul.findAll('li'):
div=li.find('div')
 if div is not None:
alink=div.find('a')
 if alink is not None:
link=alink.get('href')
 print link
html=self.enterpage(link)
self.myrss.items.append(html)
 def SaveRssFile(self,filename):
finallxml=self.myrss.to_xml(encoding='utf-8')
file=open(self.xmlpath,'w')
file.writelines(finallxml)
file.close()



if __name__=='__main__':
rssSpider=RssSpider()
rssSpider.getcontent()
rssSpider.SaveRssFile('oschina.xml')

以上所述就是本文的全部内容了,希望大家能够喜欢。

相关文章

Python爬虫框架Scrapy基本用法入门教程

Python爬虫框架Scrapy基本用法入门教程

本文实例讲述了Python爬虫框架Scrapy基本用法。分享给大家供大家参考,具体如下: Xpath <html> <head> <title>...

python使用tornado实现简单爬虫

本文实例为大家分享了python使用tornado实现简单爬虫的具体代码,供大家参考,具体内容如下 代码在官方文档的示例代码中有,但是作为一个tornado新手来说阅读起来还是有点困难的...

Python简单爬虫导出CSV文件的实例讲解

Python简单爬虫导出CSV文件的实例讲解

流程:模拟登录→获取Html页面→正则解析所有符合条件的行→逐一将符合条件的行的所有列存入到CSVData[]临时变量中→写入到CSV文件中 核心代码: ####写入Csv文件中...

Python爬虫模拟登录带验证码网站

Python爬虫模拟登录带验证码网站

爬取网站时经常会遇到需要登录的问题,这是就需要用到模拟登录的相关方法。python提供了强大的url库,想做到这个并不难。这里以登录学校教务系统为例,做一个简单的例子。 首先得明白coo...

Python使用Srapy框架爬虫模拟登陆并抓取知乎内容

Python使用Srapy框架爬虫模拟登陆并抓取知乎内容

一、Cookie原理 HTTP是无状态的面向连接的协议, 为了保持连接状态, 引入了Cookie机制 Cookie是http消息头中的一种属性,包括: Cookie名字(Name)...