educoder实训答案python_Educoder python 爬虫实战——EduCoder实训信息获取

题目链接:https://www.educoder.net/tasks/pusm8bgwkltj

看到这个题目我是震惊的,真正的“我”爬“我”自己

第一关

先看第一关,要求我们搜索机器学习相关的实训url,获取接口,https://www.educoder.net/api/search.json?keyword=%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0&type=shixun&page=1&per_page=20

从接口的url可以看到几个参数,page=1明显就是第一页了,而per_page=20,实践了一下就可以知道是每一页显示的个数,测试了一下以后发现这个参数的上线是10000,所以就先填个9999?都行吧 我填的500,因为每一页机器学习相关的好像也就9页,每一个20个,最多也就180个。

复制接口地址curl到curl.trillworks.com,直接转换为requests

cookies = {

'autologin_trustie': '*',

'_educoder_session': '*',

}

headers = {

'Pragma': 'no-cache',

'Accept-Encoding': 'gzip, deflate, br',

'Accept-Language': 'zh-CN,zh;q=0.9',

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',

'Accept': 'application/json, text/plain, */*',

'Referer': 'https://www.educoder.net/search?value=%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0',

'Connection': 'keep-alive',

'Cache-Control': 'no-cache',

}

params = (

('keyword', '\u673A\u5668\u5B66\u4E60'),

('type', 'shixun'),

('page', '1'),#页数

('per_page', '500'),#这是每一页显示的项目数,最多10000

)

拿到返回的文本后进行分析后切割。

text1=response.text.split('"results":')[1]

text2=text1[:-1]

text3=json.loads(text2)

去掉头就可以吃了,当然还有一个小尾巴,然后用json格式化

拿出每个列表中的每个字典,取【identifier】的值,其实就是一个id,然后加上头加上尾,添加到urls上面即可

urls.append('https://www.educoder.net/api/shixuns/'+x['identifier']+'challenges.json')

第二关

这道题其实会了上面那道其实也差不多啦。先贴出源代码:

for x in urls:

try:

response = requests.get(x, headers=headers, cookies=cookies)

x_dict=json.loads(response.text)

response2 = requests.get(x[:-16]+'.json', headers=headers, cookies=cookies)

xx_dict = json.loads(response2.text)

x_name=xx_dict['name']

x_comment=x_dict['description']

x_gkm=[]

for x in x_dict['challenge_list']:

x_gkm.append(x['name'])

i_dict={'实训名':x_name,'简介':x_comment,'关卡名':x_gkm}

content.append(i_dict)

except:

i=1

首先这个地方有个很狗的地方,如果直接访问https://www.educoder.net/api/shixuns/4fhemfr9/challenges.json

里面没有实训的真实名字的,需要访问https://www.educoder.net/api/shixuns/4fhemfr9.json 才能拿得到,其余的自己意会吧,有什么问题留言评论

你可能感兴趣的:(educoder实训答案python_Educoder python 爬虫实战——EduCoder实训信息获取)