| |
| |
| |
| |
| ''' |
| Download script for French tests |
| To run: |
| `python French_TST_Senior/download_script/download_tests.py` |
| ''' |
|
|
| import requests |
| from bs4 import BeautifulSoup |
| from tqdm import tqdm |
| from pathlib import Path |
| from requests.adapters import HTTPAdapter |
| from urllib3.util.retry import Retry |
| from urllib.parse import urljoin |
|
|
|
|
| def build_session( |
| max_retries: int = 3, |
| backoff_factor: int = 2, |
| session: requests.Session = None |
| ) -> requests.Session: |
| """ |
| Build a requests session with retries |
| |
| Args: |
| max_retries (int, optional): Number of retries. Defaults to 3. |
| backoff_factor (int, optional): Backoff factor. Defaults to 2. |
| session (requests.Session, optional): Session object. Defaults to None. |
| """ |
| session = session or requests.Session() |
| adapter = HTTPAdapter(max_retries=Retry(total=max_retries, backoff_factor=backoff_factor)) |
| session.mount("http://", adapter) |
| session.mount("https://", adapter) |
| session.headers.update({ |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" |
| }) |
|
|
| return session |
|
|
|
|
| def main(): |
| base_url = "https://maths-olympiques.fr/?page_id=479" |
| req_session = build_session() |
|
|
| output_dir = Path(__file__).parent.parent / "raw" / "tests" |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| resp = req_session.get(base_url) |
|
|
| if resp.status_code != 200: |
| raise Exception(f"Failed to retrieve the page. Status code: {resp.status_code}") |
|
|
| soup = BeautifulSoup(resp.text, 'html.parser') |
| link_container = soup.find('div', class_='entry-content') |
|
|
| pdf_link_eles_with_year = [] |
|
|
| year = "" |
| for ele in link_container.find_all(recursive=False): |
| if ele.name == "h4": |
| year = ele.get_text().strip(":").strip() |
| elif ele.name == "ul": |
| pdf_link_eles_with_year.append((year, ele.find_all('a', href=lambda t: '.pdf' in t and 'corrig' in t.lower() if t else False))) |
|
|
| for year, pdf_link_eles in tqdm(pdf_link_eles_with_year): |
| for pdf_link_ele in tqdm(pdf_link_eles, leave=False): |
| pdf_link = pdf_link_ele['href'] |
|
|
| output_file = output_dir / f"fr-{year}-{Path(pdf_link).name}" |
|
|
| |
| if output_file.exists(): |
| continue |
|
|
| pdf_resp = req_session.get(urljoin(base_url, pdf_link)) |
|
|
| if pdf_resp.status_code != 200: |
| print(f"Failed to download {pdf_link}") |
| continue |
|
|
| output_file.write_bytes(pdf_resp.content) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|