Python实现考试网题目答案解析脚本(网络爬虫)

前言

用Python写网络爬虫是比较常用的做法,原理是将网页下载下来后,用正则表达式清洗数据,获取目标资源。可以是文字、图片或其他URL。然后分文别类进行储存。本文只作简易的文本提取。

正文

代码是用Python2.7版本撰写,经测试可以通过。运行结果参看下文。

# -*- coding: UTF-8 -*-
import urllib2
import re

def ppkao_getanwser(questionURL) :
    questionPage = urllib2.urlopen(questionURL).read()
    # 解析题目

    questionTypeURL = re.search('以下试题来自:(.*?)<a target="_blank" href="(.*?)" >(.*?)</a>', questionPage, re.S).group(2)
    questionType = re.search('以下试题来自:(.*?)<a target="_blank" href="(.*?)" >(.*?)</a>', questionPage, re.S).group(3)
    questionTypeID = re.search('ViewAnswers\(\'//(.*?)\',\'(\d+)\'', questionPage, re.S).group(2)
    questionModel = re.search('<i class="tx">(.*?)</i>', questionPage, re.S).group(1)
    questionName = re.search('<strong class="(.*?)">(.*?)</strong>', questionPage, re.S).group(2)
    if questionModel == '简答题' :
        questionItems = []
    else :
       questionItems = re.search('</strong>(.*?)</p>', questionPage, re.S).group(1).replace('<p>', '').replace('\t', '').replace('\r\n', '').replace(',<br />', '<br />').split('<br />')
       #questionItems = re.search('</strong>(.*?)</p>', questionPage, re.S).group(1).replace('<p>', '').replace('\t', '').replace('\r\n', '').strip().replace(',<br />', '<br />').split('<br />')

    # 获取答案
    anwserURL = re.search('ViewAnswers\(\'//(.*?)\',', questionPage, re.S).group(1)
    anwserPage =  urllib2.urlopen('https://' + anwserURL).read()
    if questionModel == '简答题' :
        questionAnwser = re.search('<i class="target">试题答案</i>(.*?)<span>(.*?)<p>(.*?)</p>', anwserPage, re.S).group(3).strip()
    else :
        questionAnwser = re.search('<em class="ture-answer">(.*?)</em>', anwserPage, re.S).group(1).strip()
    # 展示
    print '题库:', questionType
    print '题库标识:', questionTypeID
    print '题库链接:', questionTypeURL
    print '题目链接:', questionURL
    print '题型:', questionModel
    print '题目:', questionName
    print '题干:', ','.join(questionItems)
    print '答案链接:', 'https://' + anwserURL
    print '答案:', questionAnwser

测试结果

ppkao_getanwser(“https://www.ppkao.com/tiku/shiti/1594015.html“)
测试结果
ppkao_getanwser(“https://www.ppkao.com/tiku/shiti/1594014.html“)
这里写图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值