zoukankan      html  css  js  c++  java
  • 中国石油大学(华东)OJ题目的HTML爬取

    这几天刷华东OJ的题,写博客还要复制HTML的代码,感觉麻烦的一批,然后就去摸鱼写了个小爬虫。。

    看一下运行效果吧~

    输入详细的pid、cid或id即可爬取相应的html代码

    一些注意要点:

    关键的还是登陆问题,程序需要在同文件夹下添加一个“headers.csv”文件用于更新和保存cookie,内容包括浏览器标头和cookie就好。也可以看我的。。。

    程序提示需要输入新的cookie时去浏览器登录一下把cookie复制进去就好。(什么,你不知道cookie从哪找?那你知道羊驼为什么会淹死吗?)

    源码:

    import requests
    from requests.exceptions import RequestException
    import re
    import csv
    #读入headers
    headers = {}
    with open('headers.csv', 'r') as f:
        rawinfos = list(csv.reader(f))
        for i in rawinfos:
            headers[i[0]] = i[1]
    def get_one_page(url, headers):
        #获取页面HTML
        try:
            response = requests.get(url, headers=headers)
            if response.status_code == 200:
                response.encoding = 'utf-8'
                return response.text
            return None
        except RequestException:
            return None
    #选择题目
    flag = int(input("是否为专题题目(0/1):"))
    if flag:
        url = "http://exam.upc.edu.cn/problem.php?cid=" + input("专题(cid):") + "&pid=" + input("题号(pid):")
    else:
        url = "http://exam.upc.edu.cn/problem.php?id=" + input("题号(id):")
    #开始爬取
    FLAG = False
    html = get_one_page(url, headers)
    while re.findall('<form id="(.*?)"', html, re.S) != []:#玄学判断cookie失效~
        #如果cookie失效,要求重新输入cookie
        headers['Cookie'] = input('your cookie may lose efficacy, input again:')
        html = get_one_page(url, headers)
        FLAG = True
    if FLAG:
        #输入有效cookie后更改headers文件
        with open('headers.csv', 'w') as f:
            writer = csv.writer(f)
            for i in headers:
                data = []
                data.append(i)
                data.append(headers[i])
                writer.writerow(data)
    #正则处理html内容
    aim = re.findall('<!-- Main component for a primary marketing message or call to action -->(.*?)<!-- /container -->',
                     html, re.S)#匹配题目内容的HTML
    rr1 = re.findall('<title>(.*?)</title>', aim[0], re.S)[0]#正则匹配第一个需要被删掉的字符串
    rr2 = re.findall('<!--EndMarkForVirtualJudge-->(.*?)</center>', aim[0], re.S)[0]#正则匹配第二个需要被删除的字符串
    tmp = aim[0]
    #开始删除
    tmp = tmp.replace("<title>" + rr1 + "</title>", '')
    tmp = tmp.replace(rr2, '')
    #输出处理好的HTML内容
    print(tmp)
    View Code
  • 相关阅读:
    windows系统中ubuntu虚拟机安装及web项目到服务上(二)
    windows系统中ubuntu虚拟机安装及web项目到服务上(一)
    每个配置xml的含义作用
    第三天气接口使用总结
    js模式学习
    mac下php环境配置
    struts2
    MySQL常用命令
    JavaMail邮件开发
    文件上传与下载
  • 原文地址:https://www.cnblogs.com/Rhythm-/p/9347270.html
Copyright © 2011-2022 走看看