html_parsers.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from html.parser import HTMLParser
  16. from typing import Dict, Iterable, List, Optional, Tuple
  17. class TestHtmlParser(HTMLParser):
  18. """A generic HTML page parser which extracts useful things from the HTML"""
  19. def __init__(self):
  20. super().__init__()
  21. # a list of links found in the doc
  22. self.links = [] # type: List[str]
  23. # the values of any hidden <input>s: map from name to value
  24. self.hiddens = {} # type: Dict[str, Optional[str]]
  25. # the values of any radio buttons: map from name to list of values
  26. self.radios = {} # type: Dict[str, List[Optional[str]]]
  27. def handle_starttag(
  28. self, tag: str, attrs: Iterable[Tuple[str, Optional[str]]]
  29. ) -> None:
  30. attr_dict = dict(attrs)
  31. if tag == "a":
  32. href = attr_dict["href"]
  33. if href:
  34. self.links.append(href)
  35. elif tag == "input":
  36. input_name = attr_dict.get("name")
  37. if attr_dict["type"] == "radio":
  38. assert input_name
  39. self.radios.setdefault(input_name, []).append(attr_dict["value"])
  40. elif attr_dict["type"] == "hidden":
  41. assert input_name
  42. self.hiddens[input_name] = attr_dict["value"]
  43. def error(_, message):
  44. raise AssertionError(message)