【功能】
从知乎网站抓取用户信息并保存到本地(JSON方式) (python 3.7版本下调试成功)
![](https://img.haomeiwen.com/i21401543/ea4fdddaa7bdbe80.jpg)
![](https://img.haomeiwen.com/i21401543/10b4bdc7b7ac1d6f.jpg)
![](https://img.haomeiwen.com/i21401543/b89e40f293821406.jpg)
【以下为代码,右上角有复制按钮,可一键复制】
#从知乎网站抓取用户信息并保存到本地(JSON方式) 【我开心 Ver:20200222.001】
import requests #导入模块库
import pandas as pd
import time
headers={ #定义网页头
#'authorization':'',#此处填写你自己的身份验证信息
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36' #此处填写你自己浏览器的User-Agent
}
user_data = []
def get_user_data(page):
for i in range(page):#翻页
url = 'https://www.zhihu.com/api/v4/members/excited-vczh/followees?include=data%5B*%5D.answer_count%2Carticles_count%2Cgender%2Cfollower_count%2Cis_followed%2Cis_following%2Cbadge%5B%3F(type%3Dbest_answerer)%5D.topics&offset={}&limit=20'.format(i*20)
response = requests.get(url, headers=headers).json()['data'] #开始爬取
user_data.extend(response) #把response数据添加进user_data
print('正在爬取第%s页: %s' % (str(i+1),url)) #显示正在爬取第几页
time.sleep(3) #设置爬取网页的时间间隔为5秒,间隔如何太短,会被屏蔽或者抓取失败
# 当**.py**文件被直接运行时,if __name__ ==’__main__'之下的代码块将被运行;当.py文件以模块形式被导入时,if __name__ == '__main__'之下的代码块不被运行。
if __name__ == '__main__':
get_user_data(5) #此处设置爬取几页
df = pd.DataFrame.from_dict(user_data) #以字典保存数据
df.to_csv('c://zhihu.csv',encoding='utf_8_sig') #保存到用户名为zhihu的csv文件中,encoding='utf_8_sig'参数是为了解决中文乱码的问题
print(df) #显示爬取结果
网友评论