| |
| |
| |
| |
| ''' |
| Download script for French TST Senior |
| To run: |
| `python French_STS/download_script/download.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, unquote |
|
|
|
|
| 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=71" |
| req_session = build_session() |
|
|
| output_dir = Path(__file__).parent.parent / "raw" |
| 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('table', {"id": 'tablepress-1'}) |
|
|
| link_eles = link_container.find_all( |
| 'a', |
| href=( |
| lambda t: |
| '.pdf' in t |
| and ('corrig' in t.lower() or 'solutions' in t.lower()) |
| if t else False |
| ) |
| ) |
|
|
| for ele in tqdm(link_eles): |
| pdf_link = ele['href'] |
|
|
| output_file = output_dir / f"fr-{unquote(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() |
|
|