-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebscraper.py
More file actions
41 lines (41 loc) · 1.09 KB
/
Copy pathwebscraper.py
File metadata and controls
41 lines (41 loc) · 1.09 KB
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
import urllib.request
from html.parser import HTMLParser
URL = 'https://ktvz.com/'
with urllib.request.urlopen(URL) as f:
data = f.read().decode()
class KTVZParser(HTMLParser):
def __init__(self):
self.in_header = False # Keep track of if we're inside a <header>
super().__init__()
def handle_starttag(self, tag, attrs):
"""Called when you get an open HTML tag"""
# On KTVZ, all the text between these tags seems to be a
# headline:
#
# <header class="story__header">
# ...
# </header>
if tag == "header" and ('class', 'story__header') in attrs:
self.in_header = True
def handle_endtag(self, tag):
"""Called when you get (or should get) a close HTML tag"""
if tag == "header" and self.in_header:
self.in_header = False
def handle_data(self, data):
"""Grab all non-tag strings"""
data = data.strip()
if data != '' and self.in_header:
print("headline:", data)
parser = KTVZParser()
parser.feed(data)