Advertisement
Guest User

Untitled

a guest
Apr 28th, 2024
608
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.55 KB | None | 0 0
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import re
  4. from selenium import webdriver
  5. from selenium.webdriver.common.by import By
  6. from selenium.webdriver.chrome.options import Options
  7. from selenium.webdriver.support.ui import WebDriverWait
  8. from selenium.webdriver.support import expected_conditions as EC
  9. from selenium.webdriver.support.ui import Select
  10. import time
  11.  
  12.  
  13. username="" #put your usename here
  14. password="" #put your password here
  15.  
  16. chrome_options = Options()
  17. chrome_options.add_argument("--headless")  # Uncomment this line to run the browser in headless mode
  18. chrome_options.add_argument("--no-sandbox")
  19. chrome_options.add_argument("--headless")
  20. chrome_options.add_argument("--disable-gpu")
  21. # Set up the WebDriver
  22. driver = webdriver.Chrome(options=chrome_options)
  23.  
  24.  
  25. def get_submission_id(url, driver):
  26.     driver.get(url)
  27.     driver.execute_script("document.getElementById('verdictName').value = 'OK';")
  28.     driver.execute_script("document.getElementById('programTypeForInvoker').value = 'cpp.g++14';")
  29.     driver.execute_script("document.querySelector('input[value=\"Apply\"]').click();")
  30.     submission_id = driver.execute_script(
  31.         "return document.querySelector('a.view-source').getAttribute('submissionid');"
  32.     )
  33.     time.sleep(0.5)
  34.     return submission_id
  35.  
  36.  
  37. def extract_num(string):
  38.     match = re.match(r'^(\d+)', string)
  39.     if match:
  40.         return match.group(1)
  41.     else:
  42.         return None
  43.  
  44.  
  45. def getproblems(url):
  46.     links_with_codes = []
  47.  
  48.     # URL of the page
  49.     # url =" https://codeforces.com/problemset/page/5?tags=800-800&order=BY_RATING_ASC"
  50.  
  51.     # Send a GET request to the URL
  52.     response = requests.get(url)
  53.  
  54.     # Parse the HTML content
  55.     soup = BeautifulSoup(response.content, 'html.parser')
  56.  
  57.     # Find all links with href containing "/problemset/problem"
  58.     problem_links = soup.find_all('a', href=lambda href: href and "/problemset/problem" in href)
  59.  
  60.     # Convert the links to the desired form and prepend "https://codeforces.com"
  61.     for link in problem_links:
  62.         original_link = link['href']
  63.         # Extracting the number and problem code from the original link
  64.         parts = original_link.split("/")
  65.         number = parts[-2]
  66.         problem_code = parts[-1]
  67.         # Constructing the full link with the correct format
  68.         full_link = f"https://codeforces.com/problemset/status/{number}/problem/{problem_code}"
  69.         links_with_codes.append((full_link, number + problem_code))
  70.  
  71.     return links_with_codes
  72.  
  73.  
  74. def get_accepted_submission(url, cd):
  75.     try:
  76.         submission_id = get_submission_id(url, driver)
  77.  
  78.         if submission_id:
  79.             pf = str(extract_num(cd))
  80.             submission_url = f"https://codeforces.com/problemset/submission/{pf}/{submission_id}"
  81.             response = requests.get(submission_url)
  82.             soup = BeautifulSoup(response.content, 'html.parser')
  83.             source_code_element = soup.find('pre', id='program-source-text')
  84.             source_code = source_code_element.text.strip()
  85.             return {"submission_id": submission_id, "source_code": source_code}
  86.  
  87.         else:
  88.             return "No accepted submission found for C++ or Python."
  89.  
  90.     except Exception as e:
  91.         return f"An error occurred: {e}"
  92.  
  93.  
  94.  
  95.  
  96. # You might need to specify the path to your webdriver executable
  97. def delay(x):
  98.     time.sleep(x)
  99.  
  100.  
  101. def codeforces_login(driver, username, password):
  102.     # Load the login page
  103.     driver.get("https://codeforces.com/enter")
  104.  
  105.     # Wait for the username or email input field
  106.     # Fill in the login form
  107.     driver.execute_script(
  108.         """
  109.        document.getElementById('handleOrEmail').value = arguments[0];
  110.        document.getElementById('password').value = arguments[1];
  111.        document.getElementsByClassName('submit')[0].click();
  112.        """,
  113.         username,
  114.         password
  115.     )
  116.  
  117.     # Wait for the login process to complete
  118.     time.sleep(5)
  119.  
  120.     # Check if login was successful
  121.     if "Problemset | Codeforces" not in driver.title:
  122.         print("Login failed.")
  123.         return True
  124.     else:
  125.         print("Login successful.")
  126.         return True
  127.  
  128.  
  129. def submit_codeforces_solution(driver, language_value, problem_code, source_code):
  130.     # Load the login page
  131.  
  132.     # Load the submission page
  133.     driver.get("https://codeforces.com/problemset/submit")
  134.     delay(1)
  135.  
  136.     # Select the language from the dropdown
  137.     driver.execute_script("document.querySelector('select[name=\"programTypeId\"]').value = arguments[0];",
  138.                           language_value)
  139.  
  140.     # Enter the problem code
  141.     driver.execute_script("document.querySelector('input[name=\"submittedProblemCode\"]').value = arguments[0];",
  142.                           problem_code)
  143.  
  144.     # Click the toggleEditorCheckbox to show the editor
  145.     driver.execute_script("document.getElementById('toggleEditorCheckbox').click();")
  146.  
  147.     # Find the textarea element by its ID and make it visible
  148.     driver.execute_script("document.getElementById('sourceCodeTextarea').style.display = 'block';")
  149.  
  150.     # Enter the source code into the textarea
  151.     driver.execute_script("document.getElementById('sourceCodeTextarea').value = arguments[0];", source_code)
  152.  
  153.     # Click the submit button
  154.     driver.execute_script("document.getElementById('singlePageSubmitButton').click();")
  155.     time.sleep(0.5)
  156.  
  157.  
  158. codeforces_login(driver, username,password)
  159.  
  160.  
  161. #control page,here,
  162. for i in range(1,93):
  163.    
  164.     with open("logger.txt","a") as f:
  165.         f.write("page : - "+str(i)+"\n")
  166.     url = f"https://codeforces.com/problemset/page/{i}?order=BY_RATING_ASC"
  167.     cnt = 0  # cur solved 366
  168.     problem_links_with_codes = getproblems(url)
  169.     start_time = time.time()
  170.     for link, problem_code in problem_links_with_codes:
  171.         if (cnt >0):
  172.             pass
  173.  
  174.         if (cnt >=0):
  175.             submission = get_accepted_submission(link, problem_code)
  176.             try:
  177.                 # login_and_submit("I_steal69", "yutabot123", problem_code, submission["language"], submission["source_code"])
  178.                 submit_codeforces_solution(driver, "50", problem_code, submission["source_code"])
  179.  
  180.                 print("Submission successful!")
  181.                 # time.sleep(0.5)
  182.             except Exception as e:
  183.                 print(f"An error occurred: {e}")
  184.         cnt += 1
  185.         print(cnt)
  186.     end_time = time.time()
  187.     execution_time = end_time - start_time
  188.     print("Execution time:", execution_time, "seconds")
  189.     with open("logger.txt", "a") as f:
  190.         f.write("took : "+str(execution_time)+" seconds\n")
  191.  
  192.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement