python之requests爬取知乎

概述

本文讲解使用python的requests模块抓取知乎

难点

知乎网站必须登录后才能浏览内容,如果不登录会跳转到登录页面。

解决

用电脑浏览器(谷歌浏览器,或者以谷歌为内核的浏览器,如:QQ浏览器、360等)登录知乎网站,登录成功后,按照下图操作:

将cookie信息粘贴到下面代码的headers中

代码

# coding=utf-8
import requests,time

'''
先登录知乎,在浏览器中将cookie信息复制粘贴到headers中
'''
headers={
    'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
    'cookie':'上图中的cookie值'
    }

def get(url):
    print('++'*50)
    #发送get请求
    with requests.get(url,headers=headers) as resp:
        #打印状态码,英文提示
        print(resp.status_code,resp.reason)
        #返回的编码
        print(resp.encoding)
        #请求的url
        print(resp.url)
        #响应头,特殊的字典类型,key不区分大小写
        print(resp.headers)
        #知乎采用ajax返回json数据
        j=resp.json()
        # print(j)
        data=j.get('data')
        next_url=j.get('paging').get('next')
        for item in data:
            print('=='*50)
            target_dict=item.get('target')
            author_dict=target_dict.get('author')
            author_name=author_dict.get('name')
            content=target_dict.get('content')
            types=target_dict.get('type')

            if types=='answer':
                '''
                如果是回答,找出问题的标题
                '''
                question_dict=target_dict.get('question')
                title=question_dict.get('title')
            elif types=='article':
                title=target_dict.get('title')
            else:
                print('未知类型---------------------')    

            # 打印分类,目前已知有文章和回答
            print('type:',types)
            print('title:',title)
            print('作者:',author_name)
            print('content:',content)

    time.sleep(3)
    get(next_url)

if __name__ == "__main__":
    url='https://www.zhihu.com/api/v3/feed/topstory/recommend?session_token=3b8092e811ba7de8d13f6fdfeb9d6840&desktop=true&page_number=2&limit=6&action=down&after_id=5'
    get(url)

原文出处:/show_1EF3R3z8j7o2.html