|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# areq.py |
| 3 | + |
| 4 | +"""Asynchronously get links embedded in multiple pages' HMTL.""" |
| 5 | + |
| 6 | +import asyncio |
| 7 | +import logging |
| 8 | +import re |
| 9 | +import sys |
| 10 | +from typing import IO |
| 11 | +import urllib.error |
| 12 | +import urllib.parse |
| 13 | + |
| 14 | +import aiofiles |
| 15 | +import aiohttp |
| 16 | +from aiohttp import ClientSession |
| 17 | + |
| 18 | +logging.basicConfig( |
| 19 | + format="%(asctime)s %(levelname)s:%(name)s: %(message)s", |
| 20 | + level=logging.DEBUG, |
| 21 | + datefmt="%H:%M:%S", |
| 22 | + stream=sys.stderr, |
| 23 | +) |
| 24 | +logger = logging.getLogger("areq") |
| 25 | +logging.getLogger("chardet.charsetprober").disabled = True |
| 26 | + |
| 27 | +HREF_RE = re.compile(r'href="(.*?)"') |
| 28 | + |
| 29 | + |
| 30 | +async def fetch_html(url: str, session: ClientSession, **kwargs) -> str: |
| 31 | + """GET request wrapper to fetch page HTML. |
| 32 | +
|
| 33 | + kwargs are passed to `session.request()`. |
| 34 | + """ |
| 35 | + |
| 36 | + # Don't do any try/except here. If either the request or reading |
| 37 | + # of bytes raises, let that be handled by caller. |
| 38 | + resp = await session.request(method="GET", url=url, **kwargs) |
| 39 | + resp.raise_for_status() # raise if status >= 400 |
| 40 | + logger.info("Got response [%s] for URL: %s", resp.status, url) |
| 41 | + html = await resp.text() # For bytes: resp.read() |
| 42 | + |
| 43 | + # Dont close session; let caller decide when to do that. |
| 44 | + return html |
| 45 | + |
| 46 | + |
| 47 | +async def parse(url: str, session: ClientSession, **kwargs) -> set: |
| 48 | + """Find HREFs in the HTML of `url`.""" |
| 49 | + found = set() |
| 50 | + try: |
| 51 | + html = await fetch_html(url=url, session=session, **kwargs) |
| 52 | + except ( |
| 53 | + aiohttp.ClientError, |
| 54 | + aiohttp.http_exceptions.HttpProcessingError, |
| 55 | + ) as e: |
| 56 | + logger.error( |
| 57 | + "aiohttp exception for %s [%s]: %s", |
| 58 | + url, |
| 59 | + getattr(e, "status", None), |
| 60 | + getattr(e, "message", None), |
| 61 | + ) |
| 62 | + return found |
| 63 | + except Exception as e: |
| 64 | + # May be raised from other libraries, such as chardet or yarl. |
| 65 | + # logger.exception will show the full traceback. |
| 66 | + logger.exception( |
| 67 | + "Non-aiohttp exception occured: %s", getattr(e, "__dict__", {}) |
| 68 | + ) |
| 69 | + return found |
| 70 | + else: |
| 71 | + # This portion is not really async, but it is the request/response |
| 72 | + # IO cycle that eats the largest portion of time. |
| 73 | + for link in HREF_RE.findall(html): |
| 74 | + try: |
| 75 | + # Ensure we return an absolute path. |
| 76 | + abslink = urllib.parse.urljoin(url, link) |
| 77 | + except (urllib.error.URLError, ValueError): |
| 78 | + logger.exception("Error parsing URL: %s", link) |
| 79 | + pass |
| 80 | + else: |
| 81 | + found.add(abslink) |
| 82 | + logger.info("Found %d links for %s", len(found), url) |
| 83 | + return found |
| 84 | + |
| 85 | + |
| 86 | +async def write_one(file: IO, url: str, **kwargs) -> None: |
| 87 | + """Write the found HREFs from `url` to `file`.""" |
| 88 | + res = await parse(url=url, **kwargs) |
| 89 | + if not res: |
| 90 | + return None |
| 91 | + async with aiofiles.open(file, "a") as f: |
| 92 | + for p in res: |
| 93 | + await f.write(f"{url}\t{p}\n") |
| 94 | + logger.info("Wrote results for source URL: %s", url) |
| 95 | + |
| 96 | + |
| 97 | +async def bulk_crawl_and_write(file: IO, urls: set, **kwargs) -> None: |
| 98 | + """Crawl & write concurrently to `file` for multiple `urls`.""" |
| 99 | + async with ClientSession() as session: |
| 100 | + tasks = [] |
| 101 | + for url in urls: |
| 102 | + tasks.append( |
| 103 | + write_one(file=file, url=url, session=session, **kwargs) |
| 104 | + ) |
| 105 | + await asyncio.gather(*tasks) # see also: return_exceptions=True |
| 106 | + |
| 107 | + |
| 108 | +if __name__ == "__main__": |
| 109 | + import pathlib |
| 110 | + import sys |
| 111 | + |
| 112 | + assert sys.version_info >= (3, 7), "Script requires Python 3.7+." |
| 113 | + here = pathlib.Path(__file__).parent |
| 114 | + |
| 115 | + with open(here.joinpath("urls.txt")) as infile: |
| 116 | + urls = set(map(str.strip, infile)) |
| 117 | + |
| 118 | + # Header - just a single, initial row-write |
| 119 | + outpath = here.joinpath("foundurls.txt") |
| 120 | + with open(outpath, "w") as outfile: |
| 121 | + outfile.write("source_url\tparsed_url\n") |
| 122 | + |
| 123 | + asyncio.run(bulk_crawl_and_write(file=outpath, urls=urls)) |
0 commit comments