這算的上是一個練習爬,學習了這麼久的正則,也懵逼了一段時間,可是一旦寫起來發現正則真給力啊!html
zip 方法在 Python 2 和 Python 3 中的不一樣:在 Python 3.x 中爲了減小內存,zip() 返回的是一個對象。如需展現列表,需手動 list() 轉換。若是須要了解 Pyhton3 的應用,能夠參考 Python3 zip()。python
''' @Modify Time @Author ------------ ------- 2019/9/8 23:50 laoalo ''' import re import requests head = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134' } def spider(url): ''' 爬取一個頁面的用戶名和他的糗事 :return: 一個列表,元素是字典 ''' response = requests.get(url=url,headers=head).text # 爬取文章 articals = re.findall(r'<div\sclass="content">\s<span>(.*?)</span>', response, re.DOTALL) str_artical = [] for i in articals: temp = re.sub('<.*>', "", i).strip() str_artical.append(temp) # 爬取用戶名 users = re.findall(r'<div class="author clearfix">.*?<a.*?>.*?</a>.*?<a.*?>\s<h2>(.*?)</a>', response, re.DOTALL) str_user = [] for i in users: temp = re.sub('<.*>', "", i) temp = re.sub('amp;', "", temp).strip() str_user.append(temp) # 彙總 funny=[] for i,j in zip(str_user,str_artical): temp = { "用戶名":i, "糗事":j } funny.append(temp) return funny if __name__ == '__main__': for i in range(1,10): print("*"*50,"這是第{}頁的糗事:\n".format(i)) url = "https://www.qiushibaike.com/hot/page/{}/".format(i) print(spider(url))