通過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