这算的上是一个练习爬,学习了这么久的正则,也懵逼了一段时间,可是一旦写起来发现正则真给力啊!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))