通过api爬取数据


一、 通过api爬取数据步骤                                      

1.设置请求头

2.使用requests包爬取api地址

3.把返回的json保存到字典中(使用json包的loads方法)

 

二、示例代码                                                           

 

import requests
import json

#1.请求头
header = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0",
    "Host":"www.zhihu.com",
}

#api接口
baseApi = "https://www.zhihu.com/api/v5.1/topics/19568808/feeds/essence?offset=10&limit=100&data[?(target.type=topic_sticky_module)].target.data[?(target.type=answer)].target.is_normal,comment_count,voteup_count,content,relevant_info,excerpt.author.badge[?(type=best_answerer)].topics&include=data[?(target.type=topic_sticky_module)].target.data[?(target.type=answer)].target.content,relationship.is_authorized,is_author,voting,is_thanked,is_nothelp"

#2.使用session请求地址
session = requests.Session()
#get请求
res = session.get(baseApi,headers=header)

#3.使用json.loads方法解析返回值
dataDict = json.loads(res.text)

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM