selenium自动填写Project Eluer答案
17

0. 背景

在做projecteuler题目时,由于需要先在vscode写代码算出答案,然后在去浏览器填写答案,刚好最近学了下selenium,就打算实战下。

1. 过程

首先,在浏览器找到网站的cookie免去登陆的过程,刚开始处理时发现只需要处理answer框和check按钮,找到对应的元素填写表单就行,后面发现答题有时也需要过验证码,刚好之前逛Linux.do时看到过ddddocr库,然后就开始在ai的帮助下尝试用起来,最后也是成功实现了自动化提交答案,成功那刻还是有点激动😁😁😁。

2. 代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from dotenv import load_dotenv
load_dotenv()  # Load environment variables from .env file
import os
import ddddocr

def submit_answer_to_site(problem_number, ans):
    ocr = ddddocr.DdddOcr(show_ad=False)

    browser = webdriver.Chrome()
    browser.get('https://projecteuler.net/login')
    # use cookie to avoid login
    # add the cookie to the browser
    # replace with your cookie values
    # get cookie value from .env avoiding hardcoding
    cookie_value = os.getenv('COOKIE')
    cookie = {
        'name': 'PHPSESSID',
        'value': '',
        'domain': '.projecteuler.net',
        'path': '/',
        'secure': False,
        'httpOnly': True
    }
    cookie['value'] = cookie_value
    browser.add_cookie(cookie)
    # navigate to the problem page
    url = f'https://projecteuler.net/problem={problem_number}' 
    browser.get(url)
    time.sleep(2)
    # exit when the problem had been solved
    try:
        noteElem = browser.find_elements(By.CLASS_NAME, 'small_notice')
        if len(noteElem) == 2:
            print(f'Problem {problem_number} already solved.')
            browser.quit()
            return
    except:
        pass

    # find the captcha image
    try:
        captchaElem = WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.ID, 'captcha_image'))
        )
        # use ddddocr to recognize the captcha
        captcha_image_data = captchaElem.screenshot_as_png
        captcha_text = ocr.classification(captcha_image_data)
        print(f'Captcha recognized: {captcha_text}')
        # find the captcha input field and enter the captcha text
        captcha_input = browser.find_element(By.ID, 'captcha')
        captcha_input.send_keys(captcha_text)
    # if there is no captcha, just continue
    except:
        print(f'Problem {problem_number} does not require a captcha.')
        pass

    # find the answer input field and submit button
    try:
        answer_input = browser.find_element(By.ID, 'guess')
    except:
        print(f'Problem {problem_number} does not have an answer input field.')
        browser.quit()
        return
    try:   
        check_button = browser.find_element(By.CSS_SELECTOR, "input[type='submit'][value='Check']")
    except:
        print(f'Problem {problem_number} does not have a submit button.')
        browser.quit()
        return
    # enter the answer
    answer_input.send_keys(str(ans))
    time.sleep(1)
    # click the submit button
    check_button.click()
    time.sleep(3)
    # check if the answer is correct
    try:
        result = browser.find_element(By.CSS_SELECTOR, "img[alt='Correct'][title='Correct']")
        print(f'Problem {problem_number} solved correctly: {ans}')
    except:
        print(f'Problem {problem_number} failed with answer: {ans}')
    finally:
        browser.quit()

3. 总结

怎么说吧,自动化提交好像还是比手动填写慢,但是这样也挺好玩的。

selenium自动填写Project Eluer答案
https://blog.wedata.club/archives/shi-yong-seleniumzi-dong-tian-xie-project-eluerda-an
作者
Administrator
发布于
更新于
许可