用python提取百度贴吧的小说

这个博客主要是发表些关于Windows Phone开发相关方面的文章的,和 http://blog.sina.com.cn/u/2391033251 同步更新。不过今天不务正业一下,发表一段python代码。这个程序主要功能是从百度贴吧,获得html文件,然后用Beautiful Soup解析html文件,提取贴吧的帖子。干什么的?其实是来看小说的,想做的更自动化一些的,但是python开始学没多长时间,暂时做到这个程度了,以后有机会会考虑增强功能的。

代码如下:

#-*- encoding: utf-8 -*-
import urllib2
import re
from BeautifulSoup import BeautifulSoup

def stripHTMLTags (html):
'''strip html tags; from http://goo.gl/EaYp5'''
return re.sub('<([^!>]([^>]|\n)*)>', '', html)

def fetch_tieba(url,localfile,ignoreFansReq=False):
'''fetch the url resource and save to localfile'''

# fetch the url resource and encode to utf-8
html = urllib2.urlopen(url).read()
html = unicode(html,'gb2312','ignore').encode('utf-8','ignore')

# extract the main content
content = BeautifulSoup(html).findAll(attrs={'class':'d_post_content'})

# write the content to localfile
myfile = open(localfile,'w')
for item in content:
item_formatted = stripHTMLTags(str(item).replace('<br />','\r\n'))
if ignoreFansReq == True :
if len(item_formatted) < 100:
continue
myfile.write(item_formatted)
myfile.write('\r\n')
print item_formatted
myfile.close()

def main():
urlTarget = "http://tieba.baidu.com/p/1234371208"
localfileTarget = './xiaoshuo2.txt'
fetch_tieba(url=urlTarget,localfile=localfileTarget,ignoreFansReq=True)

if __name__ == "__main__":
main()

 

简单说明:
1 本人使用的开发环境是 Windows 7 Ultimate 32bit + Python 2.7;依赖 Beautiful Soup (地址) ,使用版本是 BeautifulSoup-3.2.0;
2 fetch_tieba函数参数的含义:url,贴吧资源目标地址;localfile,保存到本地文件的路径;ignoreFansReq,忽略插楼、求粉等灌水信息(只是根据文字数判断,很简陋);
3 代码具有时效性,如果百度贴吧的页面DOM发生改变,程序可能失效。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值