標籤:re requests
之前看到了這道shell面試題:擷取51CTO部落格列表按時間倒序排序http://oldboy.blog.51cto.com/2561410/1860985
由於學了一段時間的python,試想著能否使用python來解題
思路:通過requests模組擷取網頁源碼,通過split()函數擷取總頁數,拼接字串擷取所有部落格地址的url。同樣,通過requests擷取所有頁面的源碼並通過正則匹配,擷取關鍵資訊,從而拼接出html頁面。
#coding:utf-8import requestsimport re,sysreload(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]# 擷取關鍵資訊並拼接htmldef 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頁面
650) this.width=650;" src="http://s5.51cto.com/wyfs02/M02/89/C2/wKioL1gcAVmTchDtAAAyUb0_Jo0894.png" title="QQ20161104113227.png" alt="wKioL1gcAVmTchDtAAAyUb0_Jo0894.png" />
使用python擷取51CTO部落格列表按時間倒序排序