Parses an HTML or XML file and returns the parsed document tree. Args: path: A file path, file-like object, or Path object to be parsed. options: HTML or XML parsing options that control the parsing behavior. chunk_size: Size of chunks to read from the file during p
(
path: typing.Union[str, typing.TextIO, typing.BinaryIO],
options: typing.Union[
_rustlib.HtmlOptions,
_rustlib.XmlOptions,
typing.Literal["html"],
typing.Literal["xml"],
] = "html",
*,
chunk_size: int = 10240,
)
| 145 | |
| 146 | |
| 147 | def parse_file( |
| 148 | path: typing.Union[str, typing.TextIO, typing.BinaryIO], |
| 149 | options: typing.Union[ |
| 150 | _rustlib.HtmlOptions, |
| 151 | _rustlib.XmlOptions, |
| 152 | typing.Literal["html"], |
| 153 | typing.Literal["xml"], |
| 154 | ] = "html", |
| 155 | *, |
| 156 | chunk_size: int = 10240, |
| 157 | ) -> TreeDom: |
| 158 | """ |
| 159 | Parses an HTML or XML file and returns the parsed document tree. |
| 160 | |
| 161 | Args: |
| 162 | path: A file path, file-like object, or Path object to be parsed. |
| 163 | options: HTML or XML parsing options that control the parsing behavior. |
| 164 | chunk_size: Size of chunks to read from the file during parsing (default is 10240 bytes). |
| 165 | |
| 166 | Returns: |
| 167 | A TreeDom object representing the parsed document tree. |
| 168 | |
| 169 | The function supports parsing files of different types (string paths, Path objects, |
| 170 | file-like objects) and handles file opening and closing automatically. |
| 171 | """ |
| 172 | from pathlib import Path |
| 173 | |
| 174 | close = False |
| 175 | |
| 176 | if isinstance(path, Path): |
| 177 | path = str(path) |
| 178 | |
| 179 | if isinstance(path, str): |
| 180 | path = open(path, "rb") |
| 181 | close = True |
| 182 | |
| 183 | try: |
| 184 | parser = Parser(options) |
| 185 | |
| 186 | while True: |
| 187 | content = path.read(chunk_size) |
| 188 | if not content: |
| 189 | break |
| 190 | |
| 191 | parser.process(content) |
| 192 | |
| 193 | return parser.finish().into_dom() |
| 194 | finally: |
| 195 | if close: |
| 196 | path.close() |