使用python获取51CTO博客列表按时间倒序排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用python获取51CTO博客列表按时间倒序排序相关的知识,希望对你有一定的参考价值。

之前看到了这道shell面试题:获取51CTO博客列表按时间倒序排序http://oldboy.blog.51cto.com/2561410/1860985

由于学了一段时间的python,试想着能否使用python来解题


思路:通过requests模块获取网页源码,通过split()函数获取总页数,拼接字符串获取所有博客地址的url。同样,通过requests获取所有页面的源码并通过正则匹配,获取关键信息,从而拼接出html页面。


#coding:utf-8

import requests
import re,sys

reload(sys)
sys.setdefaultencoding(‘utf-8‘)

# 获取页数
def page():
    url = ‘http://oldboy.blog.51cto.com/all/2561410‘
    content = requests.get(url).content
    msg = re.findall(r‘<center>(.*)</center>‘,content)[0]
    return msg.split(‘/‘)[-1].split()[0]

# 获取关键信息并拼接html
def oldboy():
    uri = ‘http://oldboy.blog.51cto.com/all/2561410/page/‘
    num = page()
    res = []
    for i in range(int(num)):
        url = uri + str(int(i)+1) 
	    content = requests.get(url).content
	    res += re.findall(r‘<a href="(/\d+/\d+)">(.*)</a>‘,content)
	    # res格式[(‘/2561410/1867160‘,‘2017\xd7\xee\xd0\xc2\xc6\xf3\xd2\xb5Shell\xc3\xe6\xca\xd4\xcc\xe2\xbc\xb0\xc6\xf3\xd2\xb5\xd4\xcb\xce\xac\xca\xb5\xd5\xbd\xb9\xb230\xb5\xc0\xb0\xb8\xc0\xfd‘),...]
    html = ‘‘
    for i in res:
	    msg = i[1].decode(‘gbk‘)
	    href = ‘http://oldboy.blog.51cto.com‘+i[0]
	    html += "<p><br></p><p>{0}</p><p><a href=‘{1}‘ target=‘_blank‘>{1}</a></p>".format(msg,href)
        # html格式"<p><br></p><p>2017最新企业Shell面试题及企业运维实战共30道案例</p><p><a href=‘http://oldboy.blog.51cto.com/2561410/1867160‘ target=‘_blank‘>http://oldboy.blog.51cto.com/2561410/1867160</a></p>..."
    with open(‘oldboy_blog.html‘,‘w‘) as f:
        f.write(html)

if __name__==‘__main__‘:
    oldboy()


html页面

技术分享


以上是关于使用python获取51CTO博客列表按时间倒序排序的主要内容,如果未能解决你的问题,请参考以下文章

企业shell面试题:获取51CTO博客列表倒序排序考试题

Python 基础 2-3 列表的反转与排序

利用Python搜索51CTO推荐博客并保存至Excel

Python 爬取51cto博客页面信息

Python 爬取51cto博客页面信息

51CTO推荐博客列表