使用python擷取51CTO部落格列表按時間倒序排序

來源:互聯網
上載者:User

標籤: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部落格列表按時間倒序排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.