selenium自动登录获取cookie+爬取在线编程网站阿尔法Coding中已完成的代码

具体思路:
之前写过一个爬取阿尔法Coding中已完成的代码的帖子,这个得手动获取cookie并复制到代码中才可以正常爬取数据。
但是通过selenium,我们可以实现自动登录,并自动获取cookie,然后直接在原有代码的基础上继续爬取数据。

selenium自动登录获取cookie+爬取在线编程网站阿尔法Coding中已完成的代码_第1张图片
通过selenium依次点击并输入内容(元素的定位直接在检查工具里copy xpath)即可,
selenium自动登录获取cookie+爬取在线编程网站阿尔法Coding中已完成的代码_第2张图片

最后登录平台获取cookie,代码如下,具体看注释:

AllinOne.py
# coding=utf-8
import json
import os
import time
from selenium import webdriver
import requests


def getCookie(str):  # 获取cookie
    wd = webdriver.Chrome(r'D:\chromedriver.exe')
    wd.implicitly_wait(10)
    wd.get('http://www.alphacoding.cn/login/')
    select__selections = wd.find_element_by_xpath(
        '//*[@id="app"]/div/div/div/div[2]/div[1]/div/div[1]/div[1]/div[2]/div[1]/div/span').click()#点击下拉列表
    select = wd.find_element_by_xpath(
        '//*[@id="app"]/div/div/div/div[2]/div[1]/div/div[1]/div[1]/div[2]/div[2]/ul[2]/li[2]').click()#选择学校
    username = wd.find_element_by_xpath('//*[@id="app"]/div/div/div/div[2]/div[1]/div/div[1]/div[2]/div[2]/input').send_keys('此处输入学号')#输入学号
    password = wd.find_element_by_xpath('//*[@id="app"]/div/div/div/div[2]/div[1]/div/div[1]/div[3]/div[2]/input').send_keys('此处输入密码')#输入密码

    login = wd.find_element_by_xpath('//*[@id="app"]/div/div/div/div[2]/div[1]/div/div[2]/button/span').click()#点击登录
    time.sleep(3)
    cookie_list = wd.get_cookies()#获取cookie
    cookie1 = cookie_list[1]['name'] + '=' + cookie_list[1]['value']
    cookie2 = cookie_list[0]['name'] + '=' + cookie_list[0]['value']
    usefulcookie = cookie1 + ';' + cookie2#cookie拼接
    # print(usefulcookie)
    wd.quit()#获取cookie后退出浏览器
    return usefulcookie


def getHTMLText(url, usefulcookie):  # 获取网页内容
    try:
        kv = {'cookie': 'null', 'user-agent': 'Mozilla/5.0'}
        kv['cookie'] = usefulcookie
        # print(kv)
        r = requests.get(url, headers=kv, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        demo = r.text
        return demo
    except:
        return ""


def grabCode(demo):  # 提取数据
    jsonstr = json.loads(demo)
    # print(type(jsonstr))
    #   加工数据
    # 输出标题
    print("题目".center(40, '*'))
    print(jsonstr['data']['lesson']['title'])  # 对字典进行访问
    # 输出内容
    print("要求".center(40, '*'))
    print(jsonstr['data']['lesson']['exercises'][0]['description']['content'])  # 对字典和列表进行访问
    # 输出代码
    print("代码".center(40, '*'))
    print(jsonstr['data']['lesson']['exercises'][0]['files'][0]['correctAnswer'])
    # 数据加工后,将题目,内容,代码拼接,相当于成品,下一步存入文件
    code = "题目".center(40, '*') + "\n" + jsonstr['data']['lesson']['title'] + "\n" + \
           "要求".center(40, '*') + "\n" + jsonstr['data']['lesson']['exercise'][0]['description']['content'] + "\n" + \
           "代码".center(40, '*') + "\n" + \
           jsonstr['data']['lesson']['exercise'][0]['files'][0]['correctAnswer']
    return code


def saveText(i, enddate, title):
    root = "d:/CrawlAlphaCoding/"
    textname = root + title[i] + ".txt"
    if not os.path.exists(root):  # 目录不存在则创建
        os.makedirs(root)
    if not os.path.exists(textname):  # 文件不存在则创建
        f = open(textname, "w+", encoding="utf-8")  # 不加encoding会导致部分文件无内容写入
        f.write(enddate)
    else:
        print("文件已存在")


def main():
    usefulcookie = getCookie(str)
    url = 'http://www.alphacoding.cn/api/courses/v3/79/chapterDetail'  # 获取章节信息,包含id和title
    jsonstr = json.loads(getHTMLText(url, usefulcookie))  # 将json格式的字符转换为dict,从文件中读取
    # print(getHTMLText(url, usefulcookie))
    batchUrl = []  # 定义列表,将id和title存入列表,便于保存文件时的使用
    title = []
    rawdate = jsonstr['data']['chapters']
    for i in rawdate:  # 第一个for循环,遍历章节,用于做url后缀访问网站
        for a in range(len(i['lessons'])):  # 第二个for循环,遍历题目,用作文件名
            # print(len(i['lessons']))
            batchUrl.append("http://www.alphacoding.cn/api/learning/v3/79/lesson/" + i['lessons'][a]['lessonId'])#将网址存入Url列表
            title.append(i['lessons'][a]['title'])

    for i in range(len(batchUrl)):
        try:  # 导学部分没有代码,会访问出错,使用try/except处理异常
            print(batchUrl[i])
            saveText(i, grabCode(getHTMLText(batchUrl[i], usefulcookie)), title)
        except:
            print("章节导航没有代码")


main()

运行结果:
selenium自动登录获取cookie+爬取在线编程网站阿尔法Coding中已完成的代码_第3张图片
selenium自动登录获取cookie+爬取在线编程网站阿尔法Coding中已完成的代码_第4张图片

你可能感兴趣的:(selenium,python,cookie)