forked from openvinotoolkit/openvino_notebooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml_reader.py
52 lines (43 loc) · 1.86 KB
/
html_reader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# code from https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/html_reader.py
import logging as log
import re
import urllib.request
from html.parser import HTMLParser
class HTMLDataExtractor(HTMLParser):
def __init__(self, tags):
super(HTMLDataExtractor, self).__init__()
self.started_tags = {k: [] for k in tags}
self.ended_tags = {k: [] for k in tags}
def handle_starttag(self, tag, attrs):
if tag in self.started_tags:
self.started_tags[tag].append([])
def handle_endtag(self, tag):
if tag in self.ended_tags:
txt = ''.join(self.started_tags[tag].pop())
self.ended_tags[tag].append(txt)
def handle_data(self, data):
for tag, l in self.started_tags.items():
for d in l:
d.append(data)
# read html urls and list of all paragraphs data
def get_paragraphs(url_list):
opener = urllib.request.build_opener()
opener.addheaders = [("User-agent", "Mozilla/5.0")]
urllib.request.install_opener(opener)
paragraphs_all = []
for url in url_list:
log.info("Get paragraphs from {}".format(url))
with urllib.request.urlopen(url) as response:
parser = HTMLDataExtractor(['title', 'p'])
charset='utf-8'
if 'Content-type' in response.headers:
m = re.match(r'.*charset=(\S+).*', response.headers['Content-type'])
if m:
charset = m.group(1)
data = response.read()
parser.feed(data.decode(charset))
title = ' '.join(parser.ended_tags['title'])
paragraphs = parser.ended_tags['p']
log.info("Page '{}' has {} chars in {} paragraphs".format(title, sum(len(p) for p in paragraphs), len(paragraphs)))
paragraphs_all.extend(paragraphs)
return paragraphs_all