python實(shí)現(xiàn)批量下載新浪博客的方法
本文實(shí)例講述了python實(shí)現(xiàn)批量下載新浪博客的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
# coding=utf-8
import urllib2
import sys, os
import re
import string
from BeautifulSoup import BeautifulSoup
def encode(s):
return s.decode('utf-8').encode(sys.stdout.encoding, 'ignore')
def getHTML(url):
#proxy_handler = urllib2.ProxyHandler({'http':'http://211.138.124.211:80'})
#opener = urllib2.build_opener(proxy_handler)
#urllib2.install_opener(opener)
req = urllib2.Request(url)
response = urllib2.urlopen(req, timeout=15)
return BeautifulSoup(response, convertEntities=BeautifulSoup.HTML_ENTITIES)
def visible(element):
'''抓取可見的文本元素'''
if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
return False
elif re.match('<!--.*-->', str(element)):
return False
elif element == u'\xa0':
return False
return True
def delReturn(element):
'''刪除元素內(nèi)的換行'''
return re.sub('(?<!^)\n+(?!$)', ' ', str(element)).decode('utf-8')
def validFilename(filename):
# windows
return re.sub('[\/:*?<>"|\xa0]', '', filename)
def writeToFile(text, filename, dirname):
if not os.path.exists(dirname):
os.makedirs(dirname)
print encode('保存到目錄'), dirname
filename = validFilename(filename)
print encode('保存文章'), filename
path = os.path.join(dirname, filename)
if not os.path.exists(path):
f = open(path, 'w')
f.write(text)
f.close()
else:
print filename, encode('已經(jīng)存在')
def formatContent(url, title=''):
'''格式化文章內(nèi)容'''
page = getHTML(url)
content = page.find('div', {'class':'articalContent'})
art_id = re.search('blog_(\w+)\.html', url).group(1)
blog_name = page.find('span', id='blognamespan').string
if title == '':
title = page.find('h2', id=re.compile('^t_')).string
temp_data = filter(visible, content.findAll(text=True)) # 去掉不可見元素
temp_data = ''.join(map(delReturn, temp_data)) # 刪除元素內(nèi)的換行符
temp_data = temp_data.strip() # 刪除文章首尾的空行
temp_data = re.sub('\n{2,}', '\n\n', temp_data) # 刪除文章內(nèi)過多的空行
# 輸出到文件
# 編碼問題
temp_data = '本文地址:'.decode('utf-8') + url + '\n\n' + temp_data
op_text = temp_data.encode('utf-8')
op_file = title + '_' + art_id +'.txt'
writeToFile(op_text, op_file, blog_name)
def articlelist(url):
articles = {}
page = getHTML(url)
pages = page.find('ul', {'class':'SG_pages'}).span.string
page_num = int(re.search('(\d+)', pages).group(1))
for i in range(1, page_num+1):
print encode('生成第%d頁文章索引'%i)
if i != 1:
url = re.sub('(_)\d+(\.html)$', '\g<1>'+str(i)+'\g<2>', url)
page = getHTML(url)
article = page.findAll('span', {'class':'atc_title'})
for art in article:
art_title = art.a['title']
art_href = art.a['href']
articles[art_title] = art_href
return articles
def blog_dld(articles):
if not isinstance(articles, dict):
return False
print encode('開始下載文章')
for art_title, art_href in articles.items():
formatContent(art_href, art_title)
if __name__ == '__main__':
sel = raw_input(encode('你要下載的是(1)全部文章還是(2)單篇文章,輸入1或者2: '))
if sel == '1':
#articlelist_url = 'http://blog.sina.com.cn/s/articlelist_1303481411_0_1.html'
articlelist_url = raw_input(encode('請輸入博客文章目錄鏈接: '))
articles = articlelist(articlelist_url)
blog_dld(articles)
else:
#article_url = 'http://blog.sina.com.cn/s/blog_4db18c430100gxc5.html'
article_url = raw_input(encode('請輸入博客文章鏈接: '))
formatContent(article_url)
希望本文所述對大家的Python程序設(shè)計(jì)有所幫助。
- Python 爬蟲爬取指定博客的所有文章
- Python采用Django開發(fā)自己的博客系統(tǒng)
- python抓取最新博客內(nèi)容并生成Rss
- 通過Python爬蟲代理IP快速增加博客閱讀量
- 如何使用python爬取csdn博客訪問量
- 使用Python實(shí)現(xiàn)博客上進(jìn)行自動翻頁
- Python實(shí)現(xiàn)新浪博客備份的方法
- 用Python的Tornado框架結(jié)合memcached頁面改善博客性能
- 使用python和Django完成博客數(shù)據(jù)庫的遷移方法
- Python使用Django實(shí)現(xiàn)博客系統(tǒng)完整版
相關(guān)文章
詳解Python中數(shù)據(jù)類型的轉(zhuǎn)換
這篇文章主要為大家詳細(xì)介紹了Python中數(shù)據(jù)類型轉(zhuǎn)換的相關(guān)資料,文中的示例代碼講解詳細(xì),具有一定的參考價值,感興趣的小伙伴可以了解一下2023-03-03
Python內(nèi)建屬性getattribute攔截器使用詳解
這篇文章主要為大家介紹了Python內(nèi)建屬性getattribute攔截器使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
python 如何對Series中的每一個數(shù)據(jù)做運(yùn)算
這篇文章主要介紹了python 實(shí)現(xiàn)對Series中的每一個數(shù)據(jù)做運(yùn)算操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
Python Pandas數(shù)據(jù)分析之iloc和loc的用法詳解
Pandas 是一個開放源碼、BSD 許可的庫,提供高性能、易于使用的數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)分析工具,它是一個強(qiáng)大的分析結(jié)構(gòu)化數(shù)據(jù)的工具集,基礎(chǔ)是 Numpy2021-11-11
Python3+Appium實(shí)現(xiàn)多臺移動設(shè)備操作的方法
這篇文章主要介紹了Python3+Appium實(shí)現(xiàn)多臺移動設(shè)備操作的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
python-Web-flask-視圖內(nèi)容和模板知識點(diǎn)西寧街
在本篇文章里小編給大家分享了關(guān)于python-Web-flask-視圖內(nèi)容和模板的相關(guān)知識點(diǎn)內(nèi)容,有需要的朋友們參考學(xué)習(xí)下。2019-08-08

