爬虫answer

爬虫爬取学堂某课程答案经验记录:
课程url:
https://www.xuetangx.com/learn/WHUT08091001005/WHUT08091001005/4230486/video/6227457
进入单元测试页面,打开调试窗口
爬虫answer
经过一番查找,找到该请求。答案就在这个请求的响应里,通过分析这个响应,写下了py脚本。(其实可以按单元查看答案,我主要是想练习python)

# -*- coding:utf-8 -*-
import requests
from jsonpath import jsonpath  # pip install jsonpath
from bs4 import BeautifulSoup


def getJson(url):
    # 在下面输入你的cookie
    cookie = 'GA1.2.; sessionid=6wl0o9467gjdp8fadrpyvtyzoq3x7vfy; _gid=GA1.2.66408200.1607174151; provider=xuetang; django_language=zh; k=29953515'
    headers = {
        'cookie': cookie,
    }
    try:
        r = requests.get(url, headers=headers)
    except:
        return 'error'
    r.encoding = 'GBK'
    if r.status_code == 200:
        return r.json()


if __name__ == "__main__":
    for cId in range(575008, 575019, 1):
        url = 'https://www.xuetangx.com/api/v1/lms/exercise/get_exercise_list/' + str(cId) + '/'
        _json = getJson(url)
        if _json.get('msg')=='No permissions':   #失败后的响应
            continue
        print('\n###', jsonpath(_json, "$.data.description"), '###')
        for html in jsonpath(_json, "$..content.Body"):
            # 使用 html parser解析 html文档
            soup = BeautifulSoup(html, 'html.parser')
            print(soup.find_all('p')[0])
        i = 1
        for item in jsonpath(_json, "$..user.answer"):
            print('第' + str(i) + '题:', item)
            i += 1

上一篇:模板方法模式(行为型)


下一篇:实现进制转换伪代码