糗事百科爬取

这算的上是一个练习爬,学习了这么久的正则,也懵逼了一段时间,但是一旦写起来发现正则真给力啊!


tips:

  • zip() 函数 :  用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。返回元组列表。
  • zip 语法:zip([iterable, ...])
  • 参数说明:iterabl -- 一个或多个迭代器

zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。如果需要了解 Pyhton3 的应用,可以参考 Python3 zip()

  • strip() 方法 :   用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
  • \s :  匹配空白,即 空格,tab键
  • re.S == re.DOTALL  :   使 . 匹配包括换行在内的所有字符
'''
@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))
代码

 

posted @ 2019-09-09 00:54  东坡肉肉君  阅读(248)  评论(0编辑  收藏  举报