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抓取京东图书评论数据

 京东图书评论有非常丰富的信息,这里面就包含了购买日期、书名、作者、好评、中评、差评等等。以购买日期为例,使用Python + Mysql的搭配进行实现,程序不大,才100行。...

python登录并爬取淘宝信息代码示例

本文主要分享关于python登录并爬取淘宝信息的相关代码,还是挺不错的,大家可以了解下。 #!/usr/bin/env python # -*- coding:utf-8 -*-...

Python爬虫常用库的安装及其环境配置

Python爬虫常用库的安装及其环境配置

Python常用库的安装 urllib、re 这两个库是Python的内置库,直接使用方法import导入即可。 在python中输入如下代码: import urllib imp...

python爬虫获取新浪新闻教学

python爬虫获取新浪新闻教学

一提到python,大家经常会提到爬虫,爬虫近来兴起的原因我觉得主要还是因为大数据的原因,大数据导致了我们的数据不在只存在于自己的服务器,而python语言的简便也成了爬虫工具的首要语言...

Python实现的爬取百度文库功能示例

本文实例讲述了Python实现的爬取百度文库功能。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- from selenium import webd...